使用一系列多个条件查询/查找MongoDB文档

时间:2017-03-04 14:50:23

标签: node.js mongodb mongoose

我有一个用户架构,其基本字段包括兴趣,位置坐标 我需要使用特定的UserId执行POST请求以获得结果

 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],[]))
    });

基本上我需要在查询内部查找查询或查询..

1 个答案:

答案 0 :(得分:0)

根据您在代码中的注释,您希望在查找查询中使用多个条件,以便满足其中一个条件并根据它返回结果。您可以使用$or$and来实现它。下面给出了与您的条件类似的示例代码。

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