How to find specific array elements in MongoDB document with query and filter with range?

MongoDBDatabaseBig Data Analytics

For this, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo351.insertOne(
... {
...
...    "_id" : "101",
...    "ProductDetails" : [
...       {
...          "ProductName" : "Product-1",
...          "ProductPrice" :500
...       },
...       {
...          "ProductName" : "Product-2",
...          "ProductPrice" :400
...       }
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo351.insertOne(
... {
...
...    "_id" : "102",
...    "ProductDetails" : [
...       {
...          "ProductName" : "Product-3",
...          "ProductPrice" :200
...       },
...       {
...          "ProductName" : "Product-4",
...          "ProductPrice" :800
...       }
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : "102" }

Display all documents from a collection with the help of find() method &mnus;

> db.demo351.find();

This will produce the following output −

{
   "_id" : "101", "ProductDetails" : [
      { "ProductName" : "Product-1", "ProductPrice" : 500 },
      { "ProductName" : "Product-2", "ProductPrice" : 400 }
   ]
}
{
   "_id" : "102", "ProductDetails" : [
      { "ProductName" : "Product-3", "ProductPrice" : 200 },
      { "ProductName" : "Product-4", "ProductPrice" : 800 }
   ] 
}

Following is the query to find specific array elements in MongoDB document with query and filter with range −

> db.demo351.aggregate([
...    {
...       $match: { _id: "102" }
...    },
...    {
...       $addFields: {
...          ProductDetails: {
...             $filter: {
...                input: "$ProductDetails",
...                cond: {
...                   $and: [
...                      { $gt: [ "$$this.ProductPrice", 600 ] },
...                      { $lt: [ "$$this.ProductPrice", 900 ] }
...                   ]
...                }
...             }
...          }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : "102", "ProductDetails" : [ { "ProductName" : "Product-4", "ProductPrice" : 800 } ] }
raja
Published on 02-Apr-2020 11:28:30
Advertisements