简体   繁体   中英

how to find all documents until a condition met in mongodb

I would like to find() any document in a collection from a skip value to a limit value for a condition, not all documents.for example, I want to get all persons until I find fifth person with black hair. not just five persons with black hair. How can I do it in mongodb? Thank you!

Get the start/end ids and then the documents for that range. Supposing you want the consecutive persons between first and fifth person with black hair:

var start = db.persons.find({"hair": "black"}).sort({_id:1}).limit(1).toArray()[0]._id;
var end = db.persons.find({"hair": "black"}).sort({_id:1}).skip(4).limit(1).toArray()[0]._id;
db.persons.find({"_id": {$gte: start, $lte: end }})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM