I suppose you have the following documents in your collection.
{ "_id" : ObjectId("56801243fb940e32f3221bc2"), "a" : 0 } { "_id" : ObjectId("56801243fb940e32f3221bc3"), "a" : 1 } { "_id" : ObjectId("56801243fb940e32f3221bc4"), "a" : 2 } { "_id" : ObjectId("56801243fb940e32f3221bc5"), "a" : 3 } { "_id" : ObjectId("56801243fb940e32f3221bc6"), "a" : 4 } { "_id" : ObjectId("56801243fb940e32f3221bc7"), "a" : 5 } { "_id" : ObjectId("56801243fb940e32f3221bc8"), "a" : 6 } { "_id" : ObjectId("56801243fb940e32f3221bc9"), "a" : 7 }
From MongoDB 3.2 you can use the .aggregate() and $slice method.
db.collection.aggregate([ { "$group": { "_id": null, "count": { "$sum": 1 }, "docs": { "$push": "$$ROOT" } }}, { "$project": { "count": 1, "_id": 0, "docs": { "$slice": [ "$docs", 2, 3 ] } }} ])
What returns:
{ "count" : 8, "docs" : [ { "_id" : ObjectId("56801243fb940e32f3221bc4"), "a" : 2 }, { "_id" : ObjectId("56801243fb940e32f3221bc5"), "a" : 3 }, { "_id" : ObjectId("56801243fb940e32f3221bc6"), "a" : 4 } ] }
You can sort a document before grouping using the $sort operator.
From MongoDB 3.0 back, you need to first $group your documents and use the $sum battery operator to return the "account" of documents; also at the same group stage you need to use $push and $$ROOT to return an array of all your documents. The next step in the pipeline is $unwind , where you denormalize this array. From there, use $skip and $limit respectively skip the first 2 documents and pass 3 documents to the next step, which is another $group .
db.collection.aggregate([ { "$group": { "_id": null, "count": { "$sum": 1 }, "docs": { "$push": "$$ROOT" } }}, { "$unwind": "$docs" }, { "$skip": 2 }, { "$limit": 3 }, { "$group": { "_id": "$_id", "count": { "$first": "$count" }, "docs": { "$push": "$docs" } }} ])
As @JohnnyHK pointed out in this comment
$group is going to read all the documents and put together an array of 20k elements with them to get three documents.
Then you should run two queries using find()
db.collection.find().skip(2).limit(3)
and
db.collection.count()