需要顺序应用两组,第二组将对第一组的结果产生影响

时间:2018-07-12 10:57:57

标签: node.js mongodb

我想基于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 个答案:

答案 0 :(得分:0)

我尝试过,它为我工作。抱歉

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