0

I have a web page where users can see data from MongoDB on a map. I want to have several check boxes, radio buttons, etc to filter what is seen on the map. If I was using MySQL I would do

query = "SELECT * FROM table WHERE x = 1" 
if checkbox == "checked":
  query += "AND WHERE y = 2"

How can I replicate that with pymongo?

1 Answer 1

6

You simply build up the query dict instead:

query = {'x': 1}
if checkbox == 'checked':
    query['y'] = 2

results = db.collection.find(query)

Doing an OR query would look like this:

query = [{'x': 1}]
if checkbox == 'checked':
    query.append({'y': 2})

results = db.collection.find({'$or': query})
Sign up to request clarification or add additional context in comments.

4 Comments

And its even cleaner to build a mongo query dynamically than it is to build raw sql text (not talking about an ORM)
That worked like a charm! Now, what if I want to do OR instead of AND?
@user1084826: You should really read the docs. Its all right there on how to format queries.
@user1084826 Again, you've just got to build up the mongo query object. I updated the answer to give you an example.

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.