gpt4 book ai didi

mongodb - mongodb 聚合中的 $replaceRoot

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

我有一个这样的集合:

{
"_id" : ObjectId("5bd1686ba64b9206349284db"),
"type" : "Package",
"codeInstances" : [
{
"name" : "a",
"description" : "a"
},
{
"name" : "b",
"description" : "b1"
},
{
"name" : "b",
"description" : "b2"
}
]
}
{
"_id" : ObjectId("5bd16ab8a64b92068d485054"),
"type" : "Package",
"codeInstances" : [
{
"name" : "a",
"description" : "a"
},
{
"name" : "b",
"description" : "b3"
}
]
}

下面的结构就是我想要的:

{
"name" : "b",
"description" : "b1"
},
{
"name" : "b",
"description" : "b1"
},
{
"name" : "b",
"description" : "b3"
}

我试过这个聚合操作:

db.getCollection('t_system_code').aggregate([
{"$unwind":"$codeInstances"},
{$match:{"codeInstances.name":"b","type" : "Package"}},
{"$project":{"codeInstances":1,"_id":0}}
]);

但是那undefined不是我想要的结构:

{
"codeInstances" : {
"name" : "b",
"description" : "b1"
}
}
{
"codeInstances" : {
"name" : "b",
"description" : "b2"
}
}
{
"codeInstances" : {
"name" : "b",
"description" : "b3"
}
}

帮助。谢谢。

最佳答案

您可以使用 $replaceRoot 尝试以下聚合

db.collection.aggregate([
{ "$match": { "codeInstances.name": "b", "type": "Package" }},
{ "$unwind": "$codeInstances" },
{ "$match": { "codeInstances.name": "b", "type": "Package" }},
{ "$replaceRoot": { "newRoot": "$codeInstances" }}
])

关于mongodb - mongodb 聚合中的 $replaceRoot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53059357/

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