Get specific elements from embedded array in MongoDB?

MongoDBDatabaseBig Data Analytics

To get specific elements, use $match with dot notation. Let us create a collection with documents −

> db.demo641.insert(
...    {
...       ProductId:101,
...       "ProductInformation":
...      (                            [
...          {
...             ProductName:"Product-1",
...             "ProductPrice":1000
...          },
...          {
...             ProductName:"Product-2",
...             "ProductPrice":500
...          },
...          {
...             ProductName:"Product-3",
...             "ProductPrice":2000
...          },
...          {
...             ProductName:"Product-4",
...             "ProductPrice":3000
...          }
...       ]
...    }
... );
WriteResult({ "nInserted" : 1 })

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

> db.demo641.find();

This will produce the following output −

{
   "_id" : ObjectId("5e9c31d46c954c74be91e6e2"), "ProductId" : 101, "ProductInformation" :
   [
      { "ProductName" : "Product-1", "ProductPrice" : 1000 },
      { "ProductName" : "Product-2", "ProductPrice" : 500 },
      { "ProductName" : "Product-3", "ProductPrice" : 2000 },
      { "ProductName" : "Product-4", "ProductPrice" : 3000 }
   ] 
}

Following is the query to get specific elements from embedded array in MongoDB

> db.demo641.aggregate([
... {$unwind: "$ProductInformation"},
... {$match: { "ProductInformation.ProductPrice": {$in :[1000, 2000]}} },
... {$project: {_id: 0, ProductInformation: 1} }
... ]).pretty();

This will produce the following output −

{
   "ProductInformation" : {
      "ProductName" : "Product-1",
      "ProductPrice" : 1000
   }
}
{
   "ProductInformation" : {
      "ProductName" : "Product-3",
      "ProductPrice" : 2000
   }
}
raja
Published on 12-May-2020 08:14:31
Advertisements