I have the following document structure
{
_id: ...,
topics: [ ... ],
posts: [ {id: 1}, {id:2}, {id: 3}]
}
I would like to find all posts that match specific ids. E.g
[2,3]
I have tried this:
db.getCollection("data")
.find({},{
posts: {
$elemMatch: {
id: {
$in: [2, 3]
}
}
}
})
but it only return one post
{
_id: ...,
posts: [ {id: 3} ]
}
I guess another way to go would be to just return all posts and filter then manually. Which one would have a better performance?
$elemMatchwill return first single matching element, for your requirement you can use $filter operator and $in operator for condition checking.