假设我有这个文件:
{
"_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" : ""
}
}
我只是想获取“广告客户”内部的特定值,例如Lowered_name.
查询时,我可以使用以下语法:
db.advertisers.find({"advertisers.lowered_name" : "conair"})
但是,它当然会返回等于查询的文档.我如何才能获得特定值“ conair”.例如,在打印语句中使用它:使用这样的代码将导致错误:
for cursor in results:
print(cursor["advertisers.lowered_name"])
如何才能做到这一点?我尝试搜索,但是我可能在某个地方错过了它?
解决方法:
您无法使用Pymongo使用“点符号”来访问嵌入字段,因为Pymongo使用词典来表示文档.
for item in db.advertisers.find({"advertisers.lowered_name" : "conair"}, {"advertisers.lowered_name": 1}):
print(item["advertisers"]["lowered_name"])
您也可以使用.distinct方法,但请记住,这只会返回唯一的“ lowered_name”列表
for item in db.advertisers.distinct("advertisers.lowered_name", {"advertisers.lowered_name" : "conair"}):
print(item)