简体   繁体   中英

Iterate through a PyMongo collection

I need to iterate through my collection and get all the values from the keys with the same name.

[
    {
        "_id": {
            "$oid": "59b3824b44e96c07dceba8de"
        },
        "place": "Yellow Stone",
        "time": "2017-09-08",
        "user": "user@gmail.com",
        "user_go": "yes"
    },
    {
        "_id": {
            "$oid": "59b4ea8644e96c37c43be33a"
        },
        "place": "Yosemite",
        "time": "2017-11-10",
        "user": "user@gmail.com",
        "user_go": "yes"
    },
    {
        "_id": {
            "$oid": "59b4ea9144e96c37c43be344"
        },
        "place": "Devils Tower",
        "time": "2017-09-10",
        "user": "user@gmail.com",
        "user_go": "yes"
    },
]

I'm wondering how I would get all the place names from from the collection based on the username. I've tried doing something similar to this:

data = db.voting.find({'user' : 'user@gmail.com'})
data = dumps(data)

parsed = json.loads(data)

for x in parsed:
     for key,value in x.items():
         print("values: {}".format(value))

As you might guess I get all the values for all the keys, how to get just the values for keys I want? I've also tried place = parsed[0]['place'] but that only returns the first "place" value not all values. I'm sure I'm missing something obvious but this is proving tricky to wrap my head around.

I also was reading through the docs and found cursour.forEach but can't find a good example of how to use it.

x['place'] is what you're looking for.

for x in parsed:
     place = x['place']
     ... # do something with place

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM