0

I am trying to query mongodb collection like below..

>>> db.ds.find({"from":{'$regex':'Pooja'}}).count()
18

But when i am appending this same query with custom string it gives me an error..

>>> a = 'Pooja'
>>> querystring = ''
>>> querystring = querystring+"'from':{'$regex':"+a+"}"
>>> querystring
"'from':{'$regex':Pooja}"
>>> db.ds.find({querystring}).count()
SyntaxError: invalid syntax
>>> 

I really need more than one parameters in querystring explicitly so i am using this way. Can anybody help me with this??

1 Answer 1

1

There are some severe errors in your code.

First of all:

db.ds.find({querystring}).count()  # SyntaxError here

The problem that this line gives SyntaxError because {object} syntax is a literal for set built-in type, which is available since Python 2.7.x version, so, here you're trying to create a set consisting of one string:

{object}  # creates set since Python 2.7
{object1: object2}  # creates dict (object1 should be [hashable][1])

Let's see an example of creating set in Python 2.7:

s = {1, 2, 3}  # Creating set of three unique elements ({} - set literal)
d = {1: 'a', 2: 'b'}  # Creating dict of number->letters ({:} - dict literal)

The second thing is that MongoDB Python driver (I assume that you use Pymongo) doesn't accept strings as queries. It has it's own API and all queries are made via dicts representing JSON objects (note, that Mongo stores all objects inside in binary representation of JSON called BSON).

So here, remember first problem, when you're trying to create set instead of dict).

Conclusion:

  1. Use dicts to create appropriate Pymongo queries.
  2. Create dicts properly (not sets).
Sign up to request clarification or add additional context in comments.

2 Comments

I did it with dictionary approach, Thanks for this. But can you elaborate more with "SyntaxError because {object} syntax is a literal for set built-in type"..
Updated answer, but you better refer to python documentation in sets: docs.python.org/library/sets.html

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.