Query for multiple parameters in MongoDB?

MongoDBDatabaseBig Data Analytics

To query for multiple parameters in MongoDB, you can use the dot(.) notation. Let us first create a collection with documents −

> db.multipleParametersDemo.insertOne(
...    {
...       "CustomerName" : "Larry",
...       "CustomerDetails" : [
...          {
...             "CustomerCountryName" : "US",
...             "CustomerBankName" : "HDFC",
...             "CustomerBalance" : 17363,
...          }
...       ],
...       "Purchase" : 1456,
...
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd10f9ce3526dbddbbfb60a")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.multipleParametersDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd10f9ce3526dbddbbfb60a"),
   "CustomerName" : "Larry",
   "CustomerDetails" : [
      {
         "CustomerCountryName" : "US",
         "CustomerBankName" : "HDFC",
         "CustomerBalance" : 17363
      }
   ],
   "Purchase" : 1456
}

Following is how you can query for multiple parameters in MongoDB −

> db.multipleParametersDemo.find({CustomerName: 'Larry', 'CustomerDetails.CustomerCountryName': 'US'}).count();

This will produce the following output −

1
raja
Published on 22-May-2019 08:40:56
Advertisements