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" ] }

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements