AJ0073 AJ0073 - 3 months ago 15
Node.js Question

Passing query conditions to db.collection.find in Node.js/Mongodb where the query string is generated

I am trying to build a NodeJS/mongodb application, where when I read a request which contains either

(XYZ > 10)
(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


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

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

Is there a way to do this?


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;

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.