gpt4 book ai didi

mongodb - Mongo聚合根据字段名收集数组元素

转载 作者:行者123 更新时间:2023-12-04 10:44:38 25 4
gpt4 key购买 nike

我有一个聚合的 mongo 文档,如下所示。有两个不同的批次(“-Minor”和“-Major”),每个批次也有“batchElements”。

{
"_id" : "123",
"info" : {
"batch" : "Batch1-Minor"
},
"batchElements" : {
"elements" : [
{ }, { }, .... { }
]
}
},
{
"_id" : "123",
"info" : {
"batch" : "Batch2-Minor"
},
"batchElements" : {
"elements" : [
{ }, { }, .... { }
]
}
},
{
"_id" : "123",
"info" : {
"batch" : "Batch3-Major"
},
"batchElements" : {
"elements" : [
{ }, { }, .... { }
]
}
},
{
"_id" : "123",
"info" : {
"batch" : "Batch4-Major"
},
"batchElements" : {
"elements" : [
{ }, { }, .... { }
]
}
}

如何收集“-Minor”和“-Major”的所有“batchElements”并创建如下文档;

输出:
  {
"_id" : "123",
"minorElements" : [
[{}, {}, {}, ..... {} ], // elements of "Batch1-Minor"
[{}, {}, {}, ..... {} ], // elements of "Batch2-Minor"
... // elements of "BatchN-Minor"
],
"majorElements" : [
[{}, {}, {}, ..... {} ], // elements of "Batch3-Major"
[{}, {}, {}, ..... {} ], // elements of "Batch4-Major"
... // elements of "BatchN-Major"
]
}

最佳答案

您可以从 $split 开始获取批次的“类型”作为 $group 的一部分_id .然后你可以运行另一个 $group制作 minormajor同一文档的部分。在最后一步你需要 $replaceRoot连同 $arrayToObject将两个数组提升到根级别。

db.collection.aggregate([
{
$group: {
_id: {
id: "$_id",
type: { $arrayElemAt: [ { $split: [ { $toLower: "$info.batch" }, "-" ] }, 1 ] }
},
docs: { $push: "$batchElements.elements" }
}
},
{
$group: {
_id: "$_id.id",
data: { $push: { k: { $concat: ["$_id.type","Elements"] }, v: "$docs" } }
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [ { _id: "$_id" }, { $arrayToObject: "$data" } ]
}
}
}
])

Mongo Playground

关于mongodb - Mongo聚合根据字段名收集数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59769471/

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