$ lookup中的MongoDB额外参数是否可能?

时间:2017-04-13 03:29:28

标签: 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", 
    "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的所有属性   - 找到所有翻译语言=“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中创建两个发现,然后在那里完成所有工作。

1 个答案:

答案 0 :(得分:1)

您必须使用其他解决方案(而非$$KEEP$$PRUNE):

  1. 展开结果并匹配您想要的语言:
  2. 添加 $unwind 阶段,然后在translate.langage字段上过滤文档:

    db.getCollection("property").aggregate([
        {  $match: {active:true}},
        {  $lookup: {
                from: "translation",
                localField: "_id",
                foreignField: "property",
                as: "translate"
            }   
        }, 
        { $unwind: "$translate"}, 
        { $match : {"translate.language": "dk"}}
    ]) 
    
    1. 拆分多个集合中的翻译集合
    2. 另一个解决方案是按langage设置一个翻译集合,例如translation_entranslation_dk等。 所以你只需要在相应的语言集合上执行 $lookup

      db.getCollection("property").aggregate([
          {  $match: {active:true}},
          {  $lookup: {
                  from: "translation_dk",
                  localField: "_id",
                  foreignField: "property",
                  as: "translate"
              }   
          }
      ])
      

      请注意,第二个选项会更快

相关问题