Mongo has the nice operator $slice, which let’s you only retrieve a sub sets of an entiry’s embedded array. From their official docs:
db.posts.find({}, {comments:{$slice: 5}}) // first 5 comments
db.posts.find({}, {comments:{$slice: -5}}) // last 5 comments
db.posts.find({}, {comments:{$slice: [20, 10]}}) // skip 20, limit 10
db.posts.find({}, {comments:{$slice: [-20, 10]}}) // 20 from end, limit 10
However I can’t find where it sais how the embedded array’s elements are ordered before being fetched this way. And, more important, can I change the ordering before $slicing them?
Unfortunately you can’t do this at current moment. Mongodb
$slicealways return documents with nested array in default (how it was inserted) order and you can’t apply any other order.Some notes:
In the next example filtering will be applied only on a root documents, and when you use $slice it return first 5 comments, but not from matched by filter “
comments.name“: