3

I am executing a query like this on a MongoDB collection:

 cursor = collection.find({"activityArray":{"$elemMatch":{"sport":0}}},{"activityArray.sport" : 1, "activityArray\|here is result object
.id":1, "endo" : 1})                                                                                                 |20166249
    for result_object in cursor[0:1]:                                                                                |here is result object
        print "here is result object"                                                                                |20166249                                                            |here is result object
        print result_object["endo"]                                                                                  |20166249
#        print result_object["activityArray.sport"]   
#        print result_object["activityArray"]["sport"]   
#        print result_object["sport"]   

Each of the commented out lines gives me a key error. How can I access those fields returned from a document within an array within a document resulting from a PyMongo query?

1 Answer 1

1

Since activityArray is an array, you need to have another loop on that list as follows:

cursor = collection.find({"activityArray": {"$elemMatch": {"sport":0 }}},{"activityArray.sport" : 1, "activityArray.id":1, "endo" : 1}) 

for result_object in cursor[0:1]:
    print result_object["endo"])
    for activity in result_object["activityArray"]:
        print activity["sport"]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I had figured this out in parallel, but what I still don't understand is that I thought $elemMatch returns only the first array element matched? Apparently it actually returns the whole array so long as one element matches?
@sunny There are two different types of $elemMatch operators: 1) for querying and the other for projection. In your case you used the former instead of the latter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.