MongoDB$lookup中的额外参数,是否可能?
我想从属性中找到所有active=true,并使用翻译聚合每条记录 但是我只想要英文版的gb,不要丹麦版的dkMongoDB$lookup中的额外参数,是否可能?,mongodb,mongodb-query,Mongodb,Mongodb Query,我想从属性中找到所有active=true,并使用翻译聚合每条记录 但是我只想要英文版的gb,不要丹麦版的dk property { "_id" : "111", "unique" : "ATL-D406", "name" : "Atlantis", "active" : true }, { "_id" : "222", "unique" : "WAT-606", "name" : "Wong Amat Tower", "acti
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的所有属性
-在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字段中筛选文档: 将翻译集合拆分为多个集合 另一个解决方案是使用langage提供一个翻译集,例如translation_en、translation_dk等。 因此,您只需在相应的langage集合上执行$lookup:
db.getCollection("property").aggregate([
{ $match: {active:true}},
{ $lookup: {
from: "translation_dk",
localField: "_id",
foreignField: "property",
as: "translate"
}
}
])
请注意,第二个选项会更快您在最后一行中错过了一个},但除此之外,它工作得非常好!!我不知道你可以在$REFLIND后进行$match。你是对的,第二种解决方案要快得多,特别是当我们使用30种不同的语言时。谢谢你教我一些新东西:-
db.getCollection("property").aggregate([
{ $match: {active:true}},
{ $lookup: {
from: "translation_dk",
localField: "_id",
foreignField: "property",
as: "translate"
}
}
])