Limiting query result in MongoDB

I have 20,000+ documents in my mongodb. I just found out that you cannot request them all at once.

So my question is:

I want my document to use find(query) , and then limit its results to only three documents, and I can choose where these documents start from.

For example, if my find() query resulted in 8 documents:

 [{doc1}, {doc2}, {doc3}, {doc4}, {doc5}, {doc6}, {doc7}, {doc 8}] 

command limit(2, 3) will give [doc3, doc4, doc5]

And I also need to get a total score for all this result (without limitation), for example: length() will give 8 (the number of final documents received as a result of the find() function)

Any suggestion? Thanks

+5
source share
2 answers

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() 
+4
source

add .skip(2).limit(3) to the end of your request

+7
source

Source: https://habr.com/ru/post/1239302/


All Articles