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