5

I am trying to do a simple query based on two conditions in MongoDB using pymongo.

I am using the sample restaurants data set from the tutorial documentation. I have:

from pymongo import MongoClient
import pymongo
import pandas as pd

client = MongoClient()

db = client.test

cursor = db.restaurants.find({"$and":[{'borough':"Manhattan"},{"grades":{'grade':"A"}}]}

for record in cursor:
    print record

I am just trying to print all the restaurants in Manhattan with a grade of 'B.' But this pulls back no results. I have also tried

cursor = db.restaurants.find({"borough":"Manhattan", "grades.grade":"B"})

but this will only filter by the first condition and won't filter by the "grade." It's exactly how it is laid out in the documentation but I can't get it to work.

1
  • Can you edit your question to include an example doc you're expecting to find? Commented Sep 28, 2015 at 21:31

2 Answers 2

7

The problem is in the second condition. grades is a subarray of grades, use $elemMatch:

db.restaurants.find({"$and": [{"borough": "Manhattan"}, {"grades": {"$elemMatch": {"grade": "A"}}}]})

Works for me.

Sign up to request clarification or add additional context in comments.

1 Comment

No dice. still pulls back all the grades.
2

I had a similar issue and it worked for me with the following syntax:

result = db.mycollection.find({"$and": [{"key1": value1}, {"key2": value2}]})

I have multiple records with the same value under key1, but I want the only one with specific value on key2. It seems to work for me.

Comments

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.