AlexEfremo
AlexEfremo

Reputation: 813

Pymongo dict element in array output

I got a database with this info:

{"_id":1, "test":6,"foo":[{"mom":5,"dad":10},{"mom":7, "dad":12}]}
{"_id":2, "test":9,"foo":[{"mom":6,"dad":20},{"mom":7, "dad":15}]}
{"_id":3, "test":10, "foo":[{"mom":10,"dad":13},{"mom":2, "dad":19}]}

and i query in mongo from db with mom=7:

cursor = foo.find({"foo.mom":7},{"foo.$":1,"_id":0, "test":1})
for key in cursor:
    print key

it prints me this:

{"test":6,"foo":[{"mom":7, "dad":12}]}
{"test":9,"foo":[{"mom":7, "dad":15}]}

if i use

print key['test']

i'll get the result of only "test"

So, the question is: how can i get the result like this:

{"test":6,"foo":[{"dad":12}]}
{"test":9,"foo":[{"dad":15}]}

i tried to use

print key["foo.dad"]

but it only returns an error

Upvotes: 0

Views: 3722

Answers (1)

Linda Qin
Linda Qin

Reputation: 1056

As the value of "foo" is saved in an array, you need to use key['foo'][0]['dad'] to print the value of 'dad' from the result.

The code I used is like this:

cursor = foo.find({"foo.mom":7},{"foo.$":1,"_id":0, "test":1})
for key in cursor:
    print key
    print key['test']
    print key['foo'][0]['dad']

And the result I got is like this:

{u'test': 6.0, u'foo': [{u'dad': 12.0, u'mom': 7.0}]}
6.0
12.0
{u'test': 9.0, u'foo': [{u'dad': 15.0, u'mom': 7.0}]}
9.0
15.0

If you want to get the result without the 'mom' field:

{"test":6,"foo":[{"dad":12}]}
{"test":9,"foo":[{"dad":15}]}

you can use the aggregation framework:

db.foo.aggregate([
    { $unwind : "$foo" },
    { $match : { "foo.mom" : 7 }}, 
    { $project : { 
          _id : 0,
          test : 1,
          "foo.dad" : "$foo.dad"
    }}, 
])

And the result is:

{
    "result" : [
        {
            "test" : 6,
            "foo" : {
                "dad" : 12
            }
        },
        {
            "test" : 9,
            "foo" : {
                "dad" : 15
            }
        }
    ],
    "ok" : 1
}

Upvotes: 3

Related Questions