[英]MongoDB: How to group nested arrays in one document?
I have the following Collection:我有以下收藏:
{
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:[{},{},{}]
}
]
}
The most i got was :我得到的最多的是:
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...
最终,我也必须对产品做同样的事情(将所有项目的所有服务的所有产品作为一个产品阵列获取并将文档返回到服务器,但首先...
10x 10倍
You need to group on null
_id
so that all services
get grouped in single document.您需要对
null
_id
进行分组,以便将所有services
分组到单个文档中。 Also $unwind
the services array before grouping, else group will give you array of arrays在分组之前还
$unwind
服务数组,否则 group 会给你数组数组
db.project.aggregate(
{$unwind: '$services'},
{$group: {_id:null, services: {$push: '$services'}}}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.