2017-09-16 14 views
0

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

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

我有两个类别:

前。 doc from eOTD_abbreviation

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

ex。 DOC从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

这将保存回缩写阵列的内容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 
    } 
) 

但是,如果聚合的结果很大,则可能会导致内存不足。

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

+1

应当指出的是,简单地把'$ unwind'直接按照'$ lookup'使'$ match'多余的,很多由于[MongoDB实际上在内部如何处理这种组合](https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/#lookup-unwind-coalescence),效率更高。还要注意,如果新的“根”_id值不是唯一的,'$ out'将会失败,但是通常优选的是在没有“批处理”请求的情况下将“全部”结果馈送到.insertMany()中。 –

相关问题