gpt4 book ai didi

node.js - MongoDB:如何将嵌套数组分组到一个文档中?

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:52 24 4
gpt4 key购买 nike

我有以下集合:

{
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:[{},{},{}]
}
]
]
}

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

10x

最佳答案

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

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

关于node.js - MongoDB:如何将嵌套数组分组到一个文档中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46450119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com