How do I get the value for a nested item inside a collection?

Suppose I have this document:

{
    "_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" : ""
    }
}

      

I just wanted to get a specific value inside "advertisers", let's say a downgraded name.

In a request, I can have a syntax like this:

db.advertisers.find({"advertisers.lowered_name" : "conair"})

      

But of course it will return documents equal to the request. How can I get the specific value of "conair". For example, using it in a print statement: using code like this will result in an error:

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

      

How can I do that? I tried searching, but hmm, maybe I am missing something?

+3


source to share


1 answer


You cannot access an inline field using "dot notation" using Pymongo, because Pymongo's dictionary is for document representation.

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

      



You can also use the method .distinct

, but remember that this will only return a list of unique "lowered_names"

for item in db.advertisers.distinct("advertisers.lowered_name", {"advertisers.lowered_name" : "conair"}):
    print(item)

      

+2


source







All Articles