3

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?

1
  • does it throwing an error or is it just not returning any data? Commented Jun 2, 2012 at 0:22

1 Answer 1

11

Here is how you can do it (there are probably multiple ways):

var query = {};

query["$or"]=[];
query["$or"].push({"field":"value1"});
query["$or"].push({"field":"value2"});
query["date_created"]="whatever";

query
{
    "$or" : [
        {
            "field" : "value1"
        },
        {
            "field" : "value2"
        }
    ],
    "date_created" : "whatever"
}

Now you should be able to run db.collection.find(query)

Sign up to request clarification or add additional context in comments.

Comments

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.