Reputation: 1113
I have data,
var data = [{name: 'n1', age: 22}, {name: 'n1', age: age: 11}, {name: 'n2', age: age: 16}, {name: 'n3', age: 22}];
and I want to get data according to my multiple conditions:
condition 1:- var query = {name: 'n1', age: 22};
condition 2:- var query = {name = '', age: 22}
What I want with a single query:
If I run condition 1 then the result should be
[{name: 'n1', age: 22}].
and if I run condition 2, then the result should be
[{name: 'n1', age: 22}, {name: 'n3', age: 22} ].
Means for second condition, query should search only with age field.
That all I want to implement in one query.
I am doing like:
$query:{$and: [{name: query.name}, {age: query.age}]}
It works for first condition but not for second. How can achieve it in one query?
Upvotes: 6
Views: 22776
Reputation: 103445
You could create a query object that can be initialised based on the two conditions above. The following snippet demonstrates this:
Populate test collection
db.test.insert([
{name: 'n1', age: 22},
{name: 'n1', age: 11},
{name: 'n2', age: 16},
{name: 'n3', age: 22}
])
Initialise conditions
var criteria = {},
condition = [
{"name": query.name},
{"age": query.age}
];
if (query.name !== "") { criteria["$and"] = condition; }
else { criteria["$or"] = condition; }
Test criteria for condition 1)
var query = {"name": "n1", "age": 22 }
printjson(criteria);
db.test.find(criteria);
Sample Output
{ "$and" : [ { "name" : "n1" }, { "age" : 22 } ] }
{ "_id" : ObjectId("56b341802ae7a05a8444cedc"), "name" : "n3", "age" : 22 }
Test criteria for condition 2)
var query = {"name": "", "age": 22 }
printjson(criteria);
db.test.find(criteria);
Sample Output
{ "$or" : [ { "name" : "" }, { "age" : 22 } ] }
{ "_id" : ObjectId("56b341802ae7a05a8444ced9"), "name" : "n1", "age" : 22 }
{ "_id" : ObjectId("56b341802ae7a05a8444cedc"), "name" : "n3", "age" : 22 }
Upvotes: 4
Reputation: 15442
Code it up so that only the fields you're interested in are in the query:
let criteria = [];
if (query.name && query.name.length > 0) {
criteria.push({ name: query.name });
}
if (query.age && query.age > 0) {
criteria.push({ age: query.age });
}
criteria = criteria.length > 0 ? { $and: criteria } : {};
Now you can pass your criteria to the query.
Upvotes: 6