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?
CodePudding user response:
If you want to achieve it via, MongoDB, you will have to achieve it via an aggregation pipeline, because you want to filter the posts
array, which is done via the $filter
operator, as suggested in the comments by @turivishal. Try this:
db.collection.aggregate([
{
"$addFields": {
"posts": {
"$filter": {
"input": "$posts",
"as": "item",
"cond": {
"$in": [
"$$item.id",
[
1,
2
]
]
}
}
}
}
}
])
In terms of performance, usually, the filtering at the DB level is better because the operators are optimized as much as possible and also it reduces the data transferred as everything unnecessary is filtered out.
CodePudding user response:
Try with below query it should work for you.
db.getCollection("data")
.find({
"posts.id": {
$in: [2, 3]
}
})