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?
MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.
The find() Method To query data from MongoDB collection, you need to use MongoDB's find() method.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With