Using pymongo/mongodb to filter based on multiple conditions including and/or?

Viewed 165

I am using the pymongo tutorial with the restaurant's database in a Zeppelin notebook.

  1. Which of the restaurants are pizzerias and have at a grade lower than C or a score greater than 19, regardless of grade?

I have tried using both $or/$and statements but I keep getting an error

%mongodb

db.resturants.find({$and :[{"cuisine": {$regex: "Pizza"}},
                           {"grades.grade" : {$ne: "A"}},
                           {"grades.grade" : {$ne: "B"}},
                           {"grades.grade" : {$ne: "C"}}]},
                   {$or : [{"cuisine": {$regex: "Pizza"}},
                           {"grades.score" : {$gt: 19}}]}).table()
1 Answers

You need to use strings for your operators:

db.resturants.find({"$and" :[{"cuisine": {$regex: "Pizza"}},
                           {"grades.grade" : {$ne: "A"}},
                           {"grades.grade" : {$ne: "B"}},
                           {"grades.grade" : {$ne: "C"}}]},
                   {"$or" : [{"cuisine": {$regex: "Pizza"}},
                           {"grades.score" : {$gt: 19}}]}).table()

Your syntax is valid in MongoDB but pymongo has to work with strings.

Related