gpt4 book ai didi

python - 如何从mongodb中获取匹配的子文档?

转载 作者:行者123 更新时间:2023-11-30 23:18:16 25 4
gpt4 key购买 nike

我有一个这样的收藏

{
"_id" : ObjectId("545dad3562fa028fb48832f0"),
"key" : "123456",
"members" : [
{
"name" : "Shiva",
"country" : "India",
"profession" : "Software"
},
{
"name" : "Neil",
"country" : "Australia",
"profession" : "Software"
},
{
"name" : "anil",
"country" : "India",
"profession" : "Software"
}

]
}

现在我想检索印度国家的记录。当我尝试这样的时候

db.user_details.find({ 'key' :'123456','members':{$elemMatch:{'country': "India"}}}, {'members.$': 1}).pretty()

执行上述代码时,我只得到第一次出现,如何从该文档获取所有匹配的子文档(例如 name:Shivaname:Anil)

最佳答案

$elemMatch 运算符以及对应的 positional $ 运算符当前仅匹配满足指定条件的第一个元素。

为了获得“多个”匹配,最好的方法是使用聚合框架:

 db.user_details.aggregate([
# Always match first to at least find the "documents" with matching elements
{ "$match": {
"members.country": "India"
}},

# Use $unwind to "de-normalize" the array as individual documents
{ "$unwind": "$members" },

# Then match again to "filter" the content down to matches
{ "$match": {
"members.country": "India"
}},

# Group back to keep an array
{ "$group": {
"_id": "$_id",
"key": { "$first": "$key" },
"members": { "$push": "$members" }
}}
])

这是从数组中“过滤”多个匹配项的基本过程。基本投影目前无法做到这一点。

这会返回:

{
"_id" : ObjectId("545dad3562fa028fb48832f0"),
"key" : "123456",
"members" : [
{
"name" : "Shiva",
"country" : "India",
"profession" : "Software"
},
{
"name" : "anil",
"country" : "India",
"profession" : "Software"
}
]
}

关于python - 如何从mongodb中获取匹配的子文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26814821/

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