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

如何在Mongodb中的一个集合上使用$lookup保存我获得的数组?,mongodb,merge,lookup,Mongodb,Merge,Lookup,我想知道如何保存文档的一部分,$lookup方法return。以下是一个例子: 如何仅将缩写数组保存到eOTD\u term集合中? 我有两个收藏: 例如,文件来源于eOTD\U缩写 { "_id" : ObjectId("59bc32fd7d7934a6a7a47d08"), "abbreviationID" : "0161-1#AB-000282#1", "termID" : "0161-1#TM-623205#1",

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

如何仅将缩写数组保存到
eOTD\u term
集合中?

我有两个收藏:

例如,文件来源于
eOTD\U缩写

    {
        "_id" : ObjectId("59bc32fd7d7934a6a7a47d08"),
        "abbreviationID" : "0161-1#AB-000282#1",
        "termID" : "0161-1#TM-623205#1",
        "abbreviation" : "CONSTR,LGHT"
    }
来自
eOTD\U术语的ex.doc

{
    "_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: [] } }
  }
]);
然后我返回(聚合返回的文档之一):

{强调文本
“_id”:ObjectId(“59BC2D7E7D7934A6A777540”),
“termID”:“0161-1#TM-623205#1”,
“概念ID”:“0161-1#01-082401#1”,
“术语”:“构造,光”,

“缩写”:[这将缩写数组的内容保存回eOTD_术语:

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
    }
)
db.eOTD\u term.insertMany(
db.eOTD_术语集合([
{
$lookup:{
发件人:“eOTD_缩写”,
localField:“termID”,
外域:“termID”,
as:“缩写”
}
},
{
$match:{缩写:{$ne:[]}
},
{
$unwind:“$缩写”
},
{
$replaceRoot:{newRoot:$缩写“}
},
]).结果,
{

ordered:false应该注意的是,简单地将
$unwind
直接放在
$lookup
之后,会使
$match
冗余,并且由于以下原因效率更高:
$out
如果新的“根”
\u id
值不是唯一的,但通常比输入“all”更可取将结果放入
.insertMany()
,而无需“批处理”请求。
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
    }
)