BrettJ
BrettJ

Reputation: 1226

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": "[email protected]",
        "user_go": "yes"
    },
    {
        "_id": {
            "$oid": "59b4ea8644e96c37c43be33a"
        },
        "place": "Yosemite",
        "time": "2017-11-10",
        "user": "[email protected]",
        "user_go": "yes"
    },
    {
        "_id": {
            "$oid": "59b4ea9144e96c37c43be344"
        },
        "place": "Devils Tower",
        "time": "2017-09-10",
        "user": "[email protected]",
        "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' : '[email protected]'})
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.

Upvotes: 1

Views: 1787

Answers (1)

cs95
cs95

Reputation: 402844

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

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

Upvotes: 4

Related Questions