Syntax error MongoDB query to find value in array with multiple criteria (range)

MongoDB query to find value in array with multiple criteria (range)



To find value in an array within a range, use $gt and $lt. Let us create a collection with documents −

> db.demo341.insertOne({
...    "Name": "Chris",
...       "productDetails" : [
...          {
...             "ProductPrice" : {
...             "Price" : 800
...          }
...       },
...       {
...          "ProductPrice" : {
...             "Price" : 400
...          }
...       },
...       {
...       "ProductPrice" : {
...          "Price" : 300
...          }
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e53ed5cf8647eb59e5620a7")
}
> db.demo341.insertOne({
...    "Name": "Chris",
...       "productDetails" : [
...          {      
...             "ProductPrice" : {
...                "Price" : 1000
...             }
...          },
...          {
...          "ProductPrice" : {
...             "Price" : 1200
...          }
...       },
...       {
...          "ProductPrice" : {
...             "Price" : 1300
...          }
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e53edc1f8647eb59e5620a8")
}

Display all documents from a collection with the help of find() method −

> db.demo341.find();

This will produce the following output −

{
   "_id" : ObjectId("5e53ed5cf8647eb59e5620a7"), "Name" : "Chris", "productDetails" : [
      { "ProductPrice" : { "Price" : 800 } }, { "ProductPrice" : { "Price" : 400 } },
      { "ProductPrice" : { "Price" : 300 } }
   ]
}
{
   "_id" : ObjectId("5e53edc1f8647eb59e5620a8"), "Name" : "Chris", "productDetails" : [
      { "ProductPrice" : { "Price" : 1000 } }, { "ProductPrice" : { "Price" : 1200 } },
      { "ProductPrice" : { "Price" : 1300 } }
   ] 
}

Following is the query to find value in the array with multiple criteria −

> db.demo341.aggregate([
...    { "$match": {
...       "productDetails": {
...          "$elemMatch": {
...          "ProductPrice.Price": {
...             "$gt": 600,
...             "$lt": 900
...          }
...       }
...    }
... }}
... ]).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e53ed5cf8647eb59e5620a7"),
   "Name" : "Chris",
   "productDetails" : [
      {
         "ProductPrice" : {
            "Price" : 800
         }
      },
      {
         "ProductPrice" : {
            "Price" : 400
         }
      },
      {
         "ProductPrice" : {
            "Price" : 300
         }
      }
   ]
}
Updated on: 2020-04-02T07:26:04+05:30

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements