I have a collection I’d like to query as follows:
- return all documents
- up to 2 comments (e.g. a slice, either 0, 1, or 2 comments)
- all comments must have views > 10
It seems like I need to create a function to evaluate each document individually, but it’s not clear how that’s done, particularly given I want to do a slice and return up to n items matching that criteria.
Sample schema:
{
title: "One",
comments: [
{
title: "comment1",
views: 9
},
{
title: "comment2",
views: 10
},
{
title: "comment3",
views: 11
},
{
title: "comment4",
views: 12
},
]
}
I want to do something like:
db.collection.find({"comments.views": {$gt: 10}}, {comments:{$slice: 2}})
But this returns any document with a comment with > 10 views, and then slices 2 comments… I want to return on those comments which have > 10 items. I cannot do it on the client AND use $slice without losing some comments, so I need to do it on the DB. Thoughts?
This is the behavior of filtering multi level embedded document, normally the matching filter would return the whole document, not the subsets.
Usually positional operator $ used to match the sub documents in updates. But the feature is not yet implemented in return specifiers.
There is an outstanding issue already in mongo Support for positional ($) operator in fields to return specifier. (Please login to vote if you really needed the feature)
So you have to handle the
part in your application by loop through all collections.