[英]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.