[英]search on multiple collections with mongodb
我想检查多个文件上是否存在特定数据。
例如,我想检查用户集合中是否存在电子邮件,如果客户集合中确实存在电子邮件,那么我想获取数据。
我已经在下面的查询中尝试过,但是由于仅检查一个集合而失败。
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();
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.