Accessing array values in a MongoDB collection to fetch a specific document


To access array values, use dot(.) notation. Let us create a collection with documents −

> db.demo326.insertOne({id:101,"ProductDetails":[{"ProductId":"Prod-101","ProductName":"Product-1"},
... {"ProductId":"Prod-102","ProductName":"Product-2"}
... ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516751f8647eb59e562074")
}
> db.demo326.insertOne({id:103,"ProductDetails":[{"ProductId":"Prod-104","ProductName":"Product-5"},
... {"ProductId":"Prod-105","ProductName":"Product-6"}
... ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516771f8647eb59e562075")
}

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

> db.demo326.find();

This will produce the following output −

{
   "_id" : ObjectId("5e516751f8647eb59e562074"), "id" : 101, "ProductDetails" : [
      { "ProductId" : "Prod-101", "ProductName" : "Product-1" },
      { "ProductId" : "Prod-102", "ProductName" : "Product-2" }
   ]
}
{
   "_id" : ObjectId("5e516771f8647eb59e562075"), "id" : 103, "ProductDetails" : [
      { "ProductId" : "Prod-104", "ProductName" : "Product-5" },
      { "ProductId" : "Prod-105", "ProductName" : "Product-6" }
   ]
}

Following is the query to access the array in a MongoDB collection and fetch a specific document −

> db.demo326.find({"ProductDetails.ProductId":"Prod-104"});

This will produce the following output −

{
   "_id" : ObjectId("5e516771f8647eb59e562075"), "id" : 103, "ProductDetails" : [
      { "ProductId" : "Prod-104", "ProductName" : "Product-5" },
      { "ProductId" : "Prod-105", "ProductName" : "Product-6" }
   ] 
}

Updated on: 02-Apr-2020

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements