简体   繁体   中英

mongodb query : getting N results with a filter on a field

I use mongodb and I'm trying to make a request but I need help. I need to query on my user collection which contains a field "country".

example :

{
    "name" : "John",
    "country" : "FR"
}

For example, I want to get 30 users from France. If there are 30 users or more from France in the db, it's ok, it returns 30 users from France. If there are just 12 users (less than 30) from France, I want to get those 12 users AND 18 others users (to have 30), whatever the country.

I want to know if it's possible with a classical request or I have to use MapReduce

I believe you can't do this in one query.

  • Get the number of documents with country: "FR"
  • If this number greater or equal 30 then get exactly 30 documents using the cursor.limit method. In case this number is less than 30 then get all document where country: 'Fr' and extend the result with another query where country not equal to FR using .apply() and the .push method.

     var count = db.collection.count({ "country": "FR" }); var result = []; if (count >= 30) { result = db.collection.find({ "country": "FR" }).limit(30).toArray(); } if (count < 30 ) { result = db.collection.find({ "country": "FR" }).toArray(); result.push.apply(result, db.collection.find({ "country": { "$ne": "FR" }}).limit(30-count).toArray()); } 

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