gpt4 book ai didi

mongodb - 蒙戈 : how to retrieve ONLY subdocs that match certain properties

转载 作者:可可西里 更新时间:2023-11-01 09:55:03 24 4
gpt4 key购买 nike

例如,有一个名为 test 的集合,其中包含以下文档:

{
"_id" : ObjectId("5692ac4562c824cc5167379f"),
"list" : [
{
"name" : "elem1",
"type" : 1
},
{
"name" : "elem2",
"type" : 2
},
{
"name" : "elem3",
"type" : 1
},
{
"name" : "elem4",
"type" : 3
},
{
"name" : "elem4",
"type" : 2
}
]
}

假设我想检索 list 中匹配的那些子文档的列表:

  • 类型 = 2

我尝试了以下查询:

db.getCollection('test').find({
'_id': ObjectId("5692ac4562c824cc5167379f"),
'list.type': 1
})

但我得到的结果包含 list 中的 every 子文档,我猜这是因为 list 中至少有一个文档是输入等于 1。

取而代之的是,我想获得的结果是 list 中匹配 'list.type': 1 的每个子文档:

{
"_id" : ObjectId("5692ac4562c824cc5167379f"),
"list" : [
{
"name" : "elem1",
"type" : 1
},
{
"name" : "elem3",
"type" : 1
}
]
}

...所以 $$elemMatch 并不是我真正想要的,因为它们只返回第一个匹配的元素。

有人知道如何实现我的目标吗?

最佳答案

db.myCol.aggregate([ 
{ $unwind: "$list" },
{ $match: { "list.type":1 } },
{ $group: { "_id":"$_id", list: {$push:"$list"}} }
])

关于mongodb - 蒙戈 : how to retrieve ONLY subdocs that match certain properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710018/

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