Schema
[
{
_id:"doc1",
type:"SR",
title:"...",
description:"...",
author:"5",
posts:[
{
author:"1",
title:"..."
},
{
author:"2",
title:"..."
},
{
author:"1",
title:"..."
}
]
},
{
_id:"doc2",
type:"SA",
title:"...",
description:"...",
posts:[],
author:"5"
}
]
Every Document will have type either SA or SR. If type is SA then posts will be an empty array, otherwise it'll non empty.
Now, i want to get document and array elements based on certain conditions.
- if type is
SAandauthorId=5then return the entire document. - if type is
SRthen return the elements of posts whereauthorId=1
When type is
SAthen i would like to gettitle,description,..of the document otherwise get thepostsby filter.
My Query
Using mongoose
Blog.find({
$or: [
{
$and: [
{ type: "SA" },
{ authorId:"5" }
]
},
{
"posts.authorId": "1"
}
]
}, {
posts: {
$filter: {
input: "$posts",
as: "post",
cond: {
$eq: ["$$post.authorId", "1"]
}
}
}
})
.then(posts => {
console.log(posts)
})
.catch(err => {
console.log(err);
})
Returned document
[
{
_id:"doc1",
posts:[
{
author:"1",
title:"..."
},
{
author:"1",
title:"..."
}
]
},
{
_id:"doc2",
posts:[]
}
]