简体   繁体   中英

Query/Find MongoDB documents with series of multiple conditions

I have a User schema with basic fields which include interests, location co-ordinates I need to perform POST request with a specific UserId to get the results

  app.post('api/users/search/:id',function(err,docs) { //find all the documents whose search is enabled. //on documents returned in above find the documents who have atleast 3 common interests(req.body.interests) with the user with ':id' // -----OR----- //find the documents who stay within 'req.body.distance' compared to location of user with':id' //Something like this return User .find({isBuddyEnabled:true}), .find({"interests":{"$all":req.body.interests}}), .find({"_id":req.params.id},geoLib.distance([[req.body.gcordinates],[])) }); 

Basically i need to perform find inside find or Query inside query..

As per your comments in the code you want to use multiple conditions in your find query such that either one of those condition is satisfied and returns the result based on it. You can use $or and $and to achieve it. A sample code with conditions similar to yours is given below.

find({
  $or:[
       { isBuddyEnabled:true },
       { "interests": { "$all":req.body.interests }},
       { $and:[ 
               { "_id":req.params.id }, 
               { geoLib.distance...rest_of_the_condition }
              ] 
       }
      ]
});

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