简体   繁体   English

如何在mongodb中使用aggregrate和$ lookup在第二个集合上应用条件

[英]How to apply condition on second collection using aggregrate and $lookup in mongodb

I am totally stuck with one condition in MEAN Js. 我完全受MEAN Js的一个条件困扰。 I have written my code below : 我在下面写了我的代码:

apiRouter.post('/findhospitalbyname', function(req, res) {

    Hospital.aggregate([
    {
        "$match":{
        title: { '$regex': '.*' + req.body.name + '.*', $options: 'i' }
        }
    },
    {   
        "$lookup": {  
            "localField": "_id",   
            "from": "favorites",         
            "foreignField": "hospital_id", 
       // "pipeline": [{ 
       //    "$match": {"user_id": mongoose.Types.ObjectId(req.body.user_id)}
       //  }],
            "as": "datafind"  
        } 
  } 
],   
function(err, hospital) {
            if (err) {
                return res.send({ 'user_data': err, 'error': 1 });
            }
            if (hospital.length != 0) {
                return res.send({ 'data': hospital, 'error':0});
            } else {
                return res.send({ 'data': '', 'error':2, 'msg': 'No data found' });
            }
        })   
});

This is my code. 这是我的代码。 Here hospital is my first collection and favourite is my second collection. 在这里,医院是我的第一个收藏品,我最喜欢的是我的第二个收藏品。 I want to add a condition on second collection. 我想在第二个集合上添加一个条件。 For first collection my code is working fine but it is not working for the second collection. 对于第一个集合,我的代码运行正常,但对于第二个集合却不起作用。 There are some commented lines also which are showing my second collection where condition. 也有一些注释行显示了我的第二个收藏集的状况。 Please reply if you have any solution. 如果您有任何解决方案,请回复。

I will try to use a unwind, match, group stages to get the result you need: 我将尝试使用展开,比赛,小组赛阶段来获得所需的结果:

Hospital.aggregate([
{
    "$match":{
       title: { '$regex': '.*' + req.body.name + '.*', $options: 'i' }
    }
},
{   
    "$lookup": {  
        "from": "favorites",  
        "localField": "_id",        
        "foreignField": "hospital_id", 
        "as": "datafind"  
        } 
  },
  {
    "$unwind" : "$datafind"
  },
  { 
   "$match": {"$datafind.user_id": mongoose.Types.ObjectId(req.body.user_id)}
  },
  {
      $group: 
          {
              _id : "$_id" 
          }
  } 
],//the other code...

If you want to use pipeline first you need to know the version of your mongo database, pipeline only works on v3.6+ and the above code works on v3.2+. 如果要首先使用管道,则需要知道mongo数据库的版本,管道仅适用于v3.6 +,而上述代码适用于v3.2 +。 So yes mongo introduce and helpful conditional for lookup but remains on your database version. 因此,是的,mongo引入了有用的查找条件,但仍保留在您的数据库版本中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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