python - 在 pymongo 查询中,我想从嵌套文档中获取特定数据

标签 python mongodb pymongo

我在 mongodb 中存储了以下文档

{
    "_id" : ObjectId("5c13b65ef169123748e18ecb"),
    "Countries" : [ 
        {
            "States" : [ 
                {
                    "Cities" : [ 
                        "Eshkashem", 
                        "Fayzabad", 
                        "Jurm", 
                        "Khandud", 
                        "Qal'eh-ye Panjeh"
                    ],
                    "StateName" : "Badakhshan"
                }, 
                {
                    "Cities" : [ 
                        "Bala Morghab", 
                        "Qal'eh-ye Naw"
                    ],
                    "StateName" : "Badgis"
                }
            ],
            "CountryName" : "Afghanistan"
        }, 
        {
            "States" : [ 
                {
                    "Cities" : [ 
                        "Berat", 
                        "Polican", 
                        "Ure Vajgurore"
                    ],
                    "StateName" : "Berat"
                }, 
                {
                    "Cities" : [ 
                        "Bulqize"
                    ],
                    "StateName" : "Bulqize"
                }
            ],
            "CountryName" : "Albania"
        }
    ]
}

我想要的是,我想获取countryName为Afganisthan的数据

我尝试过以下查询

loc_country = loc.find({"Countries.CountryName":"Afghanistan"}) 

但它给出了所有记录,而不仅仅是阿富汗

请帮助我,我被困住了。

提前致谢!

最佳答案

您可以使用positional operator :

loc_country = loc.find(
   { "Countries.CountryName":"Afghanistan"},
   { 'Countries.$': 1 }
)

如果可能,您应该考虑使用每个文档包含一个国家/地区的数据模型,以便于查找。 (如果有道理的话)

关于python - 在 pymongo 查询中,我想从嵌套文档中获取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53781342/

相关文章:

python - 如何创建一个Python脚本来制作多个bash脚本?

python - matplotlib热图反转数据?

mongodb - 如果已经存在具有相同姓名和姓氏的人,如何防止多个 goroutines 在人员集合中插入文档?

python - 使用 pymongo 对同一索引执行多个正则表达式匹配

python - 使用 NetCDF 文件转置 x 射线数据集

Python readline() 和 Counter 在很长的行上导致 MemoryError

javascript - 过滤 OrionJS 中某个角色可以查看的文档

mysql - 将单个非重复数据存储到数据库的最佳方法是什么?

python - Pymongo:如何检查字段是否存在

mongodb - 如何将序数位置传递到 Pymongo 中的更新文档中以进行 $inc 更新