【问题标题】:How to get the value for a nested item inside a collection?如何获取集合中嵌套项的值?
【发布时间】:2017-03-21 14:58:56
【问题描述】:

假设我有这个文件:

{
    "_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"])

如何做到这一点?我试过搜索,但嗯,我可能在某个地方错过了它?

【问题讨论】:

  • 你试过db.advertisers.distinct("advertisers.lowered_name")吗?
  • @Veeram 嗨,我认为 distinct 仍会返回一个完整的文档。就像 findOne 一样。我需要的只是获取 ads.lowered_name 的值
  • 使用投影:.find({"advertisers.lowered_name" : "conair"}, {"advertisers.lowered_name": 1})
  • @Veeram 啊,我刚试过。我确实得到了不同值的值,但是在整个集合中。我需要在循环中获取单个值以进行操作
  • @M.StyvaneSoukossi 足够接近,但执行 'db.advertisers.find({"_id":id}, {"advertisers.lowered_name"}) 将导致过滤结果,我想我可以如果我做了 'print(cursor[advertisers])',则打印出 '{"lowered_name" : "conair"}

标签: python mongodb mongodb-query pymongo


【解决方案1】:

您无法使用 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)

【讨论】:

    猜你喜欢
    • 2016-07-03
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多