如何通过在Mongodb中的一个集合上使用$ lookup来保存我得到的数组?

时间:2017-09-16 16:44:23

标签: mongodb merge lookup

我想知道如何保存文档的一部分,$ lookup方法返回给我。这是一个例子:

如何只将缩写数组保存到eOTD_term集合中?

我有两个系列:

离。来自eOTD_abbreviation

的文档
    {
        "_id" : ObjectId("59bc32fd7d7934a6a7a47d08"),
        "abbreviationID" : "0161-1#AB-000282#1",
        "termID" : "0161-1#TM-623205#1",
        "abbreviation" : "CONSTR,LGHT"
    }

离。来自eOTD_term

的文档
{
    "_id" : ObjectId("59bc2d7e7d7934a6a7777540"),
    "termID" : "0161-1#TM-623205#1",
    "conceptID" : "0161-1#01-082401#1",
    "term" : "CONSTRUCT,LIGHT",
}

termID是我在两个集合中都存在的唯一密钥。

我尝试了以下内容:

db.eOTD_term.aggregate([
  {
    $lookup: {
      from: "eOTD_abbreviation",
      localField: "termID",
      foreignField: "termID",
      as: "abbreviation"
    }
  },
  {
    $match: { abbreviation: { $ne: [] } }
  }
]);

我回来了(聚合返回的文档之一):

{emphasized text
    "_id" : ObjectId("59bc2d7e7d7934a6a7777540"),
    "termID" : "0161-1#TM-623205#1",
    "conceptID" : "0161-1#01-082401#1",
    "term" : "CONSTRUCT,LIGHT",
    "abbreviation" : [  <----------- THIS ARRAY 
        {
            "_id" : ObjectId("59bc32fd7d7934a6a7a47d08"),
            "abbreviationID" : "0161-1#AB-000282#1",
            "termID" : "0161-1#TM-623205#1",
            "abbreviation" : "CONSTR,LGHT"
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

这会将缩写数组的内容保存回eOTD_term:

db.eOTD_term.insertMany(
    db.eOTD_term.aggregate([
      {
        $lookup: {
          from: "eOTD_abbreviation",
          localField: "termID",
          foreignField: "termID",
          as: "abbreviation"
        }
      },
      {
        $match: { abbreviation: { $ne: [] } }
      },
      {
        $unwind: "$abbreviation"
      },
      {
       $replaceRoot: { newRoot: "$abbreviation" }
      },
    ]).result,
    {
    ordered: false <-- prevents from failing on unique constraints
    }
)

但是,如果聚合的结果很大,则可能会耗尽内存。

您也可以尝试使用“$ out”阶段而不是insertMany:How do I append Mongo DB aggregation results to an existing collection?