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

标签 python mongodb mongodb-query aggregation-framework

我有一个这样的收藏

{
    "_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/

相关文章:

python - 如何更新动画 matplotlib 图中的刻度标签

python - 安装 matplotlib 后,在 Spyder 中导入 pytorch 会导致内核崩溃

python - generator.throw() 有什么用?

正则表达式 : capturing group?

javascript - Mongoose.connection ('once' ) 是什么意思

python - 如何输出多行csv?

algorithm - Memcache 驱逐监控系统

mongodb - 如何使用 MongoDb 聚合 3 个集合的计数/总和?

mongodb - 我如何解决 : 'MongoError: $where is not allowed in this atlas tier' ?

mongodb - 如何在 mongodb 聚合中将毫秒转换为日期?