我想从属性中找到所有 active=true,并将每个记录与翻译汇总在一起!我只想要英文文本“gb”,而不是丹麦文本“dk”
property
{
"_id" : "111",
"unique" : "ATL-D406",
"name" : "Atlantis",
"active" : true
},
{
"_id" : "222",
"unique" : "WAT-606",
"name" : "Wong Amat Tower",
"active" : true
}
translation
{
"_id" : "aaa",
"language" : "gb",
"property" : "111",
"texts" : "Great Condo with Pool View and Balcony"
},
{
"_id" : "bbb",
"language" : "dk",
"property" : "111",
"texts" : "Lækker Lejlighed med Pool udsigt og Balkon"
},
{
"_id" : "ccc",
"language" : "gb",
"property" : "222",
"texts" : "Luxury with Direct Beach Front"
},
{
"_id" : "ddd",
"language" : "dk",
"property" : "222",
"texts" : "Luksus direkte på Stranden"
}
据我所知,Mongodb 只允许 $lookup 中的一个字段匹配,除了非常复杂的 $redact $$KEEP $$PRUNE(这似乎是一种非常复杂的方法)之外,有没有办法做到这一点?或者我只做两个单独的发现会更好吗?或者有没有办法将两个独立发现的结果结合起来并投影您想要的字段?像: - 找到 active = true 的所有属性 - 找到所有翻译 where language = "gb" - 组合它们并投影一些字段......
db.getCollection("property").aggregate(
// Find all active properties
{
$match: {active:true}
},
// Find matching translation record
{
$lookup: {
from: "translation",
localField: "_id",
foreignField: "property",
as: "translate"
}
}
)
我能想到的唯一方法是从js中找到两个,然后在那里做所有的工作。
您必须使用其他解决方案(比$$KEEP
和$$PRUNE
):
添加一个$unwind
阶段,然后在translate.langage
field上过滤文档:
db.getCollection("property").aggregate([
{ $match: {active:true}},
{ $lookup: {
from: "translation",
localField: "_id",
foreignField: "property",
as: "translate"
}
},
{ $unwind: "$translate"},
{ $match : {"translate.language": "dk"}}
])
另一种解决方案是按语言收集一个翻译集合,例如translation_en
,translation_dk
等等。所以你只需要$lookup
在相应的语言集合上做:
db.getCollection("property").aggregate([
{ $match: {active:true}},
{ $lookup: {
from: "translation_dk",
localField: "_id",
foreignField: "property",
as: "translate"
}
}
])
请注意,第二个选项会更快
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句