MongoDB:如何在一个文档中对嵌套数组进行分组? [英] MongoDB: How to group nested arrays in one document?
问题描述
我有以下收藏集:
{
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:[{},{},{}]
}
]
}
我需要返回包含所有服务的数组的文档:
I need to return a document with an Array of all 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:[{},{},{}]
}
]
}
我得到的最多的是:
db.projects.aggregate({"$group":{"_id":"services","services":{"$push":"$services"}}})
但这会返回一个包含数组数组的文档,而我想要一个对象数组:
But this returns a document with an array of arrays and i want an array of objects:
{
_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:[{},{},{}]
}
]
]
}
我无法弄清楚数组的聚集,连接或并集或其他任何形式. 最终,我还必须对产品做同样的事情(将所有项目的所有服务的所有产品都作为一个产品阵列,并将文档返回到服务器,但首先要这样做...
I can't figure out the arrays aggregation or join or union or whatever. Eventually i will have to do the same for the products also (getting all the products of all services of all projects as one array of products and return a document to the server but first thing first...
10倍
推荐答案
您需要对null
_id
进行分组,以便将所有services
分组在单个文档中.
同样,在分组之前$unwind
服务数组,否则分组将为您提供数组数组
You need to group on null
_id
so that all services
get grouped in single document.
Also $unwind
the services array before grouping, else group will give you array of arrays
db.project.aggregate(
{$unwind: '$services'},
{$group: {_id:null, services: {$push: '$services'}}}
)
这篇关于MongoDB:如何在一个文档中对嵌套数组进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!