如何获取集合中嵌套项的值?

2024-09-24 00:31:50 发布

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

假设我有这个文件:

{
    "_id" : ObjectId("4e2f2af16f1e7e4c2000000a"),
    "location" : {
        "geometry" : [
            [ 123, 23.45321 ],
            [ 124.55632, 43.256 ]
        ]
    },
    "advertisers" : {
        "created_at" : ISODate("2011-07-26T21:02:19Z"),
        "category" : "Infinity Pro Spin Air Brush",
        "updated_at" : ISODate("2011-07-26T21:02:19Z"),
        "lowered_name" : "conair",
        "twitter_name" : "",
        "facebook_page_url" : "",
        "website_url" : "",
        "user_ids" : [ ],
        "blog_url" : ""
    }
}

我只是想了解“广告商”里面的具体价值,比如说降低姓名。在

查询时,我可以有这种语法:

^{pr2}$

但当然,它将返回与查询相等的文档。我怎样才能得到具体的值“conair”。例如,在print语句中使用它:使用这样的代码将导致错误:

for cursor in results:
    print(cursor["advertisers.lowered_name"])

如何做到这一点?我试着找,但我可能在什么地方找不到了?在


Tags: 文件nameidurllocationcursoratobjectid
1条回答
网友
1楼 · 发布于 2024-09-24 00:31:50

不能使用Pymongo使用“dot notation”访问嵌入字段,因为Pymongo使用字典来表示文档

for item in db.advertisers.find({"advertisers.lowered_name" : "conair"}, {"advertisers.lowered_name": 1}):
    print(item["advertisers"]["lowered_name"])

您也可以使用.distinct方法,但要记住,这只会返回一个唯一的“lowered\u name”列表

^{pr2}$

相关问题 更多 >