【问题标题】:Mongo Aggregate document with more than 1 array具有多个数组的 Mongo 聚合文档
【发布时间】:2018-12-24 22:37:56
【问题描述】:

在 $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...}],
    ]
}

Planning 和 Request 是数组。

我喜欢 $unwind 两个数组,然后只保留 Planning.MainField === Request.MainField 的文档

首先,我想到的解决方案是加入两个阵列,这是一个“长期”解决方案。

如果可能的话,我想玩聚合。

谢谢。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您可以使用$expr 来匹配文档中的字段

    db.collection.aggregate([
      { "$unwind": "$Planning" },
      { "$unwind": "$Request" },
      { "$match": { "$expr":
        { "$eq": ["$Planning.MainField", "$Request.MainField"] }
      }}
    ])
    

    【讨论】:

    • 刚刚找到了另一个解决方案,不过我会用这个,比较简单!谢谢!
    【解决方案2】:

    我找到了解决办法:

    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  }
            },
        ],
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多