gpt4 book ai didi

mongodb - 在 Mongo 中连接嵌套数组

转载 作者:行者123 更新时间:2023-12-04 10:45:22 24 4
gpt4 key购买 nike

我的收藏中有以下架构:

{
_id: ObjectId,
foo: [
{
bar_id: ObjectId,
bar_list: [
{...},
{...},
]
},
{
bar_id: ObjectId,
bar_list: [
{...},
{...},
]
}
...
]
],
relations: {
relation_type: [
{
relation_id: ObjectId,
...
}
]
...
}
}


我希望创建一个与输入文档具有类似结构的新文档(新文档中不需要 relations),但它是 relation_id 上的聚合。和哪里 bar_list每个输入文档的数组已连接(包括重复)。

为了显示:

文件 1
{
_id: 1,
foo: [
{
bar_id: 77,
bar_list: [
{a, b},
{c, d},
]
},
{
bar_id: 88,
bar_list: [
{u, v},
{w, x},
{y, z},
]
}
]
],
relations: {
relation_type: [
{
relation_id: 666,
...
}
]
...
}
}

文件2
{
_id: 2,
foo: [
{
bar_id: 77,
bar_list: [
{a, b},
{e, f},
{g, h},
]
},
{
bar_id: 88,
bar_list: [
{u, v},
]
}
]
],
relations: {
relation_type: [
{
relation_id: 666,
...
}
]
...
}
}

输出文件
{
foo: [
{
bar_id: 77,
bar_list: [
{a, b},
{c, d},
{a, b},
{e, f},
{g, h},
]
},
{
bar_id: 88,
bar_list: [
{u, v},
{w, x},
{y, z},
{u, v},
]
}
]
],
}


过滤匹配 relations.relation_type.relation_id 的第一部分简单。但是如何基于 bar_id 连接数组并根据需要格式化结果?这是我到目前为止所拥有的:

db.getCollection('example').aggregate([
{'$match': {'relations.relation_type.relation_id': 666}},
// Some sore of $group, $mergeObjects or $concatArrays next?
])

任何帮助表示赞赏。

最佳答案

解释

  • $unwind我们变平了 foo .
  • 现在我们$group来自 bar_id并积累 bar_list带有 key:pair 的数组值。
  • 我们使用 $reduce连接成单个数组的运算符 bar_list数组
  • $group帮助我们积累insde foo顶级文档。
  • (可选)$project删除 _id领域

  • db.collection.aggregate([
    {
    "$match": {
    "relations.relation_type.relation_id": 666
    }
    },
    {
    $unwind: "$foo"
    },
    {
    $group: {
    _id: "$foo.bar_id",
    bar_list: {
    $push: "$foo.bar_list"
    }
    }
    },
    {
    $project: {
    _id: 0,
    bar_id: "$_id",
    bar_list: {
    $reduce: {
    input: "$bar_list",
    initialValue: [],
    in: {
    $concatArrays: [
    "$$value",
    "$$this"
    ]
    }
    }
    }
    }
    },
    {
    $group: {
    _id: null,
    foo: {
    $push: "$$ROOT"
    }
    }
    },
    {
    $project: {
    _id: 0
    }
    }
    ])

    MongoPlayground

    关于mongodb - 在 Mongo 中连接嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59730659/

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