4

I am trying to build a NodeJS/mongodb application, where when I read a request which contains either (XYZ > 10) OR (XYZ < 15). I would like to generate a query string on the go. And then do a search in a certain Mongodb Collection. The following will work:

db.event.find( { 'data.XYZ': {'$lt':15} } ) // This works.

But I would like to do this:

var qstr1="{ \'data.XYZ\': {\'$lt\':15} // I would generate this possibly

db.event.find(qstr1)

When I try to pass the query condition as a string to db.collection.find() it returns me the entire collection.

I am using mongoskin for the application. This however does not work even via the Mongo Shell.

Is there a way to do this?

ma08
  • 3,654
  • 3
  • 23
  • 36
DJ0073
  • 43
  • 1
  • 5

2 Answers2

6

You're ultimately generating a query object, not a string, so build the query object up programmatically:

var query = {};
var field = 'data.XYZ';
var operator = {};
operator['$lt'] = 15;
query[field] = operator;
db.event.find(query);

If you really want to keep things as a string, you can parse the string into a query object using JSON.parse:

var qstr1="{ \"data.XYZ\": {\"$lt\":15} }";
var query = JSON.parse(qstr1);

Note that JSON.parse requires that keys are surrounded by double quotes (not single quotes) and isn't available in the shell.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • JohnnyHK, Thanks for the response!! I shall try it out and let you know. What does query[field] = operator mean? Where can I find more documentation on the "query" object ? Can I build complex queries using the above mentioned mechanism. Sorry for so many questions, I am anewbie to Javascript/Mongodb et al. – DJ0073 Mar 07 '15 at 08:47
  • @AJ0073 `query` and `operator` are just plain JavaScript objects so they can be as complex as you like. `query[field] = operator` means add a field to the `query` object named the value of `field` and assign it the `operator` object as a value. – JohnnyHK Mar 07 '15 at 14:31
0

Create a JSON string like this:

{ 
    "specilities.specility_name":"cosmetic",
    "specilities.countries.country_code":"91",
    "specilities.countries.states.state_name":"maharashtra",
    "specilities.countries.states.cities.city_name":"mumbai",
    "specilities.countries.states.cities.procedures.procedure_name":"ssss" 
}
    

and in find pass parameter as

abc.find(JSON.parse(str_temp_query), callback);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459