Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to dynamically build MongoDB query?
To build query dynamically, you need to write some script. Let us first create a collection with documents −
> db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["MongoDB","MySQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cef5c5def71edecf6a1f69a")
}
> db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["C","C++"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cef5c73ef71edecf6a1f69b")
}
> db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["MongoDB","Java"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cef5c8bef71edecf6a1f69c")
}
Display all documents from a collection with the help of find() method −
> db.dynamicQueryDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cef5c5def71edecf6a1f69a"),
"Name" : "John",
"Subject" : [
"MongoDB",
"MySQL"
]
}
{
"_id" : ObjectId("5cef5c73ef71edecf6a1f69b"),
"Name" : "John",
"Subject" : [
"C",
"C++"
]
}
{
"_id" : ObjectId("5cef5c8bef71edecf6a1f69c"),
"Name" : "John",
"Subject" : [
"MongoDB",
"Java"
]
}
Following is the query to dynamically build MongoDB query −
> function findDocument(subject) {
var find = {};
if (subject.length == 0)
find["$nin"] = subject;
else
find["$in"] = subject;
return find;
}
> var sub = ["MySQL","MongoDB"];
> var myDoc = findDocument(sub);
> db.dynamicQueryDemo.aggregate([{
$match: {
"Subject": myDoc,
}
}]);
This will produce the following output −
{ "_id" : ObjectId("5cef5c5def71edecf6a1f69a"), "Name" : "John", "Subject" : [ "MongoDB", "MySQL" ] }
{ "_id" : ObjectId("5cef5c8bef71edecf6a1f69c"), "Name" : "John", "Subject" : [ "MongoDB", "Java" ] }Advertisements