2

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?

Shivan Dragon
  • 15,004
  • 9
  • 62
  • 103

1 Answers1

3

Unfortunately you can't do this at current moment. Mongodb $slice always return documents with nested array in default (how it was inserted) order and you can't apply any other order.

Some notes:

  1. Embedded arrays always keep their order (as items was inserted)
  2. Currently if you filter on embedded array values, mongodb return all nested array values, not only matched. See more details in the jira bug.

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":

db.posts.find({"comments.name": "Test comment"}, {comments:{$slice: 5}})
Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134