使用mongodb搜索多个集合

使用mongodb搜索多个集合,mongodb,find,aggregation-framework,Mongodb,Find,Aggregation Framework,我想检查多个文档中是否存在特定数据 例如,我想检查电子邮件是否存在于用户集合和客户集合中,如果它确实想要获取数据 我尝试了下面的查询,但它失败了,因为它只检查一个集合 db.t_usermasters.aggregate([ { $match: { "email" : "test@test.com" } },{ $lookup: { from: "t_customermasters", localField: "email"

我想检查多个文档中是否存在特定数据

例如,我想检查电子邮件是否存在于用户集合和客户集合中,如果它确实想要获取数据

我尝试了下面的查询,但它失败了,因为它只检查一个集合

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

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();

您需要在
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();

我试着这样做`var isExisits=function(emailId){var user=db.t_usermasters.count({email:emailId});var customer=db.t_customermasters.count({email:emailId});if(user>1){return db.t_usermasters.find({email:emailId}).pretty();}else{return db.t_customermasters.find}({email:emailId}).pretty();}}var data=isExisits(“test@test.com“;”它现在正在提供正确的输入它正在返回空白的详细信息
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 */
}