MongoDB:如何在一个文档中对嵌套数组进行分组?

时间:2017-09-27 14:10:34

标签: node.js mongodb meteor mongodb-query

我有以下收藏:

{
    id: 23423-dsfsdf-32423,
    name: Proj1,
    services: [
         {
            id:sdfs-24423-sdf,
            name:P1_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-24jhh-sdf,
            name:P1_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-2jnbn3-sdf,
            name:P1_Service3,
            products:[{},{},{}]
         }
    ]
},
{
    id: 23423-cxcvx-32423,
    name: Proj2,
    services: [
         {
            id:sdfs-xvxcv-sdf,
            name:P2_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-xvwqw-sdf,
            name:P2_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-erdfd-sdf,
            name:P2_Service3,
            products:[{},{},{}]
         }
    ]
}

我需要返回一个包含所有服务数组的文档:

{
    services: [
         {
            id:sdfs-24423-sdf,
            name:P1_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-24jhh-sdf,
            name:P1_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-2jnbn3-sdf,
            name:P1_Service3,
            products:[{},{},{}]
         },
         {
            id:sdfs-xvxcv-sdf,
            name:P2_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-xvwqw-sdf,
            name:P2_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-erdfd-sdf,
            name:P2_Service3,
            products:[{},{},{}]
         }
     ]
}

我得到的最多是:

db.projects.aggregate({"$group":{"_id":"services","services":{"$push":"$services"}}})

但是这会返回一个包含数组数组的文档,我想要一个对象数组:

{
    _id:"services",
    services:[
        [
            {
            id:sdfs-24423-sdf,
            name:P1_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-24jhh-sdf,
            name:P1_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-2jnbn3-sdf,
            name:P1_Service3,
            products:[{},{},{}]
         }
        ],
        [
            {
            id:sdfs-xvxcv-sdf,
            name:P2_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-xvwqw-sdf,
            name:P2_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-erdfd-sdf,
            name:P2_Service3,
            products:[{},{},{}]
         }
        ]
    ]
}

我无法弄清楚数组聚合或连接或联合或其他什么。 最终我还必须为产品做同样的事情(将所有项目的所有服务的所有产品作为一个产品阵列并将文档返回到服务器但首先要做的事情......

10倍

1 个答案:

答案 0 :(得分:3)

您需要对null _id进行分组,以便将所有services分组到单个文档中。 同样在分组之前$unwind服务数组,否则group将为您提供数组数组

db.project.aggregate(
  {$unwind: '$services'},
  {$group: {_id:null, services: {$push: '$services'}}}
)