在mongodb中加入两个集合,其中相同的键值包含在数组中

时间:2018-01-17 14:02:54

标签: mongodb mongodb-query

我有两个收藏品

collection1

{
  _id:ObjectId("5a5e62dae4b0189610784ca9"),
  name:"project1",
  "cause":[{
            indications : [{
                            pattern: "(.*Failed to read artifact)"
                          }]
          }]
}

collection2

{
 _id : ObjectId("58229558e4b05d3853a6a501"),
 "categories" : [
              "CompilationFailure"
                ],
 "indications" : [
        {
            "pattern" : "(.*Failed to read artifact)"
        }],

}

我想得到的结果是:

{
  _id:ObjectId("5a5e62dae4b0189610784ca9"),
  name:"project1",
  "categories" : [
          "CompilationFailure"
            ],
  "cause":[{
            indications : [{
                            pattern: "(.*Failed to read artifact)"
                          }]
          }]
}

我可以通过模式键加入两个馆藏吗?我尝试使用$ lookup语法但它失败了。有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

那应该让你前进:

db.getCollection('collection1').aggregate({
    $lookup:
     {
       from: "collection2",
       localField: "cause.indications.pattern",
       foreignField: "indications.pattern",
       as: "categories"
     }
}, {
    $addFields: { // transform into desired structure
        "categories": { $arrayElemAt: [ "$categories.categories", 0 ] } // select the first value only to get rid of the nested array, not sure if that works for all your records/cases...
    }
})