I am using the Node.js driver for MongoDB and have no trouble constructing query objects outside of the call to find() until I attempt to introduce an $or construct into the mix.
I am attempting to dynamically generate the query because I have a variable number of parameters and would prefer to NOT have as many calls to collection.find as I have parameters.
To that end I am using a query as simple as:
var query = {};
query['name'] = 'Steve';
query['date_created'] = '<some date>';
mongo_collection.find(query, function(err, c) {});
However, when I attempt to use $or the whole process falls apart.
I have tried each of the following with no joy:
var query = {};
1.
query[$or] = [ { 'field' : 'value1' }, { 'field' : 'value2' } ];
query['date_created'] = '<some date>';
2.
query = { $or : [ { 'field' : 'value1' }, { 'field' : 'value2' } ] };
query['date_created'] = '<some date>';
3.
query = eval("[ { 'field' : 'value1' }, { 'field' : 'value2' } ]");
query['date_created'] = '<some date>';
In every case the $or is wrapped in quotes (honestly I am not sure if this is the problem or not…) and the query fails.
Is there any way to accomplish this?
Here is how you can do it (there are probably multiple ways):
Now you should be able to run db.collection.find(query)