gpt4 book ai didi

mongodb - 根据条件字段合并两个对象

转载 作者:行者123 更新时间:2023-12-04 02:30:33 25 4
gpt4 key购买 nike

假设我们有以下来自聚合管道的文档:

[
{
"_id": ObjectId("5a934e000102030405000000"),
"description": "description for item 1",
"item_code": "00001"
},
{
"_id": ObjectId("5a934e000102030405000001"),
"description": "description for item 2",
"item_code": "00002"
},
{
"_id": ObjectId("5a934e000102030405000002"),
"description": "description for item 3",
"item_code": "00003"
},
{
"_id": ObjectId("5a934e000102030405000003"),
"extrafield": "extra field for item 2",
"item_code": "00002"
}
]

如何将具有相同 item_code 的文档合并为一个,同时保留所有属性?期望的结果:

[
{
"description": "description for item 1",
"item_code": "00001"
},
{
"description": "description for item 2",
"extrafield": "extra field for item 2",
"item_code": "00002"
},
{
"description": "description for item 3",
"item_code": "00003"
}
]

我尝试了不同的 $group 模式但没有成功:(

Here's mongodb playground

最佳答案

你可以试试,

  • $group by item_code,使用 $mergeObjects$$ROOT
  • 合并对象
  • $replaceWith 将根对象替换为根
db.collection.aggregate([
{
$group: {
_id: "$item_code",
root: { $mergeObjects: "$$ROOT" }
}
},
{ $replaceWith: "$root" }
])

Playground

关于mongodb - 根据条件字段合并两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64414123/

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