在$ match和$ project之后,我具有以下文档结构:
{
"_id" : ObjectId("5a764de08337490ff57c7dc1"),
"Lote" : "id", --> Unique Index
"Planning" : [
{MainField:10, field1:value, field2:value},
{MainField:20,...},
{MainField:30...}
],
"Request" : [
{MainField:10, field1:value, field2:value},
{MainField:20,...},
{MainField:30...}],
]
}
计划和请求是数组。
我喜欢$ unwind这两个数组,然后只保留那些Planning.MainField === Request.MainField的文档
首先,我想到的解决方案是将两个数组连接在一起,这是一个“长期”解决方案。
如果可能,我想进行汇总。
谢谢。
答案 0 :(得分:1)
您可以使用$expr
来匹配文档中的字段
db.collection.aggregate([
{ "$unwind": "$Planning" },
{ "$unwind": "$Request" },
{ "$match": { "$expr":
{ "$eq": ["$Planning.MainField", "$Request.MainField"] }
}}
])
答案 1 :(得分:0)
我找到了解决方法:
db.getCollection("works").aggregate(
// Pipeline
[
// Stage 1 - Filter documents not Finished and size of array Request >0
{
$match: { Finished:{$ne:true}, Request:{$gt:{$size:0}} }
},
// Stage 2 - Project needed fields
{
$project: {Lote:1,"Planning.Fase":1,"Planning.MachineName":1,"Planning.OprID":1,"Planning.StartSetupReal":1,"Planning.StartProdReal":1,"Planning.EndProdReal":1,Request:1}
},
// Stage 3 - $unwind Planning Array
{
$unwind: { path : "$Planning"}
},
// Stage 4 - Filter unwind documents with
{
$match: { $and:[ {"Planning.field1":{$ne:''}},{"Planning.Field2":{$eq:''}}]}
},
// Stage 5 - Unwind Request Array
{
$unwind: { path : "$Request"}
},
// Stage 6 - Create new field that compares two fields in same document
{
$addFields: { "PlanReq": {"$eq":["$Planning.MainField","$Request.MainField"]} }
},
// Stage 7 - Filter documents that MainFields of the arrays are equal
{
$match: { "PlanReq":true }
},
],
);