在pymongo查询中,我想从嵌套的documen中获取特定的数据

2024-09-29 03:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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"}) 

但它提供了所有的记录,而不仅仅是一个组织

请帮帮我,我累坏了

提前谢谢


Tags: 文档idmongodbcountriesloccitiesstateseh
1条回答
网友
1楼 · 发布于 2024-09-29 03:32:05

您可以使用positional operator

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

如果可能的话,您应该考虑一个数据模型,每个文档有一个国家/地区,以便于查找(如果有意义的话)

相关问题 更多 >