代码之家  ›  专栏  ›  技术社区  ›  kamlesh paliwal

按顺序分两组,第二组对第一组结果有影响

  •  0
  • kamlesh paliwal  · 技术社区  · 7 年前

    我想基于factoryId字段分组我的数据,然后每个工厂将有多个订单希望再次基于orderId分组,因为每个订单可以包含多个项目。在这里,我给出了我的数据的例子,我需要什么,我尝试的第一组。

    { 
    "_id" : ObjectId("5b3e270c42d8004cea382e87"),  
    "factoryId" : ObjectId("5aa76190cef23a1561b8056c"), 
    "productId" : ObjectId("5aa78c66cef23a1561b80893"), 
    "orderId" : ObjectId("5b3e270c42d8004cea382e86"), 
    "generatedOrderId" : "3985-166770-4554", 
    "productName" : "Lakme Lotion"
    },
    { 
    "_id" : ObjectId("5b3e270c42d8004cea382e88"), 
    "factoryId" : ObjectId("5b39aed32832f72062e51c23"), 
    "productId" : ObjectId("5b3cb96139cec8341df52c4b"), 
    "orderId" : ObjectId("5b3e270c42d8004cea382e86"), 
    "generatedOrderId" : "3985-166770-4554", 
    "productName" : "Coke"   
    },
    { 
    "_id" : ObjectId("5b3e27b07fe0d94d62b76b2a"),  
    "factoryId" : ObjectId("5aa76190cef23a1561b8057c"), 
    "productId" : ObjectId("5ac21075ac347a5fbf355028"), 
    "orderId" : ObjectId("5b3e27b07fe0d94d62b76b27"),  
    "generatedOrderId" : "3985-755507-7484", 
    "productName" : "Spoon"
    }
    

    {
     "factoryId":ObjectId("5aa76190cef23a1561b8057c"),
     "orders":[
            {
            "orderId":ObjectId("5b3e270c42d8004cea382e86")
            "items":[
                 {
                  "productName":"Lakme Lotion"
                 },
                 {
                  "productName":"Coke"
                 } 
    
             ] 
            }
          ]
    }
    

    有人能帮我吗?。如有任何帮助,我们将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  0
  •   kamlesh paliwal    7 年前

    我试过了,对我很有帮助。对不起的

    db.getCollection("transactions").aggregate(
    [
        { 
            "$group" : {
                "_id" : "$orderId", 
                "items" : {
                    "$push" : "$$ROOT"
                }
            }
        }, 
        { 
            "$project" : {
                "orderId" : "$_id", 
                "items" : "$items", 
                "_id" : 0
            }
        }, 
        { 
            "$unwind" : {
                "path" : "$items", 
                "preserveNullAndEmptyArrays" : false
            }
        }, 
        { 
            "$group" : {
                "_id" : "$items.factoryId", 
                "orders" : {
                    "$push" : "$$ROOT"
                }
            }
        }, 
        { 
            "$project" : {
                "factoryId" : "$_id", 
                "orders" : "$orders", 
                "_id" : 0
            }
        }
    ]
    );
    
    推荐文章