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

How do I save the array I get by using $lookup on one collection in Mongodb?

我想知道如何保存文档的一部分,$lookup 方法对我来说 return。这是一个例子:

如何只将缩写数组保存到 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: [] } }
  }
]);

然后我回来了(聚合文档之一 returns):

{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"
        }
    ]
}

这会将缩写数组的内容保存回 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: