2

I have 2 variables, sent from ajax, like name and age, their default value is '*'.

when name and age are set, like name = 'a', age = 20, I can query in mongodb(pymongo):

info = list(db.test.find({'name': name, 'age': age}))

But there is time age or name is unset, I have to write:

if age == '*' and name == '*':
    info = list(db.test.find())
elif name == '*':
    info = list(db.test.find({'age': age}))
elif age == '*':
    info = list(db.test.find({'name': name}))

Is there way that I can write a single query? like:

info = list(db.test.find({'name': name, 'age': age}))
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
lzhmqq
  • 35
  • 4

2 Answers2

0

One option would be to treat * as {'$exists': True}:

name = {'$exists': True} if name == '*' else name
age = {'$exists': True} if age == '*' else age

info = list(db.test.find({'name': name, 'age': age}))

Or, better solve it on the python side by keeping name and age in the dictionary:

params = {}
if name != '*':
    params['name'] = name
if age != '*':
    params['age'] = age

info = list(db.test.find(params))
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

It is unclear what you want the query to return, what the initial values of age and name are. Please create a reproducible example (give an example of some sample docs, the query you are running, what is being returned and what you would like to see returned).

Are you looking for all documents where name (or age) is unset?

db.col.find({'name':'*'})

Are you looking for all documents where name=name or age=age?

db.col.find({ '$or': [{'name': name } , {'age': age} ] })

Please specify what specifically you want the query to return.

I disagree with alecxe however, you shouldn't 'solve on the python side'. You should do more research on how to write queries in MongoDB and let the database cluster do all of the heavy lifting in terms of processing. Just my .02.

rawkintrevo
  • 659
  • 5
  • 16
  • The reason I've chosen to suggest a python-side is that this `*` special value is an application-level thing - hence, it should be handled on the same level. Though, personally I am not happy with both options I've provided :) Thanks. – alecxe Dec 14 '14 at 05:43