简体   繁体   English

使用mongodb搜索多个集合

[英]search on multiple collections with mongodb

I want to check if particular data is present on multiple documents or not. 我想检查多个文件上是否存在特定数据。

eg I want to check if email exists in user collection and customer collection if it does then want to fetch the data. 例如,我想检查用户集合中是否存在电子邮件,如果客户集合中确实存在电子邮件,那么我想获取数据。

I have tried below query but it fails as it checks only one collection. 我已经在下面的查询中尝试过,但是由于仅检查一个集合而失败。

db.t_usermasters.aggregate([
{
    $match: {
        "email" : "test@test.com"
    }
},{
    $lookup: {
        from: "t_customermasters",
        localField: "email",
        foreignField: "email",
        as: "UserDetails"    
  }
}
]).pretty();

Try this code: 试试这个代码:

db.t_usermasters.aggregate([
{
    $match: {
        "email" : "test@test.com"
    }
},{
    $lookup: {
        from: "t_customermasters",
        localField: "email",
        foreignField: "email",
        as: "UserDetails"    
  }
}, {
    $match: { 
    UserDetails: { $exists: true, $not: {$size: 0} } 
 } 
}

]).pretty();

You need to actually lookup in t_customermasters and project down by conditioning with empty array 您实际上需要在t_customermasters进行查找,并通过使用空数组进行调节来进行下推

db.t_usermasters.aggregate([
        {
            $match: {
                "email" : "test@test.com"
            }
        },
        {
            $lookup: {
                from: "t_customermasters",
                localField:"email",
                foreignField:"email",
                as: "UserDetails"    
          }
        },
        {
            $project:{
                _id:true,
                email:true,
                emailExistInBoth:{
                    $cond:{
                        if:{
                            $eq:[{$size:"$UserDetails"},0]
                        },
                        then:false,
                        else:true
                    }
                }
            }
        },
        {
            $match:{
                "emailExistInBoth":true
            }
        }
        ]).pretty();
if(db.t_usermasters.count({email: 'test@test.com'}) 
     && db.t_customermasters.count({email: 'test@test.com'})) {

   /* fetch your data here
      you can associate these two collections by using a customerId field in your 
      usermasters collection and then populate it ('customerId') 
      while fetching the data from usermasters collection */
}

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

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