Fetch a specific document in MongoDB with array elements



To fetch a specific document, use dot notation in MongoDB find(). Let us create a collection with documents −

> db.demo672.insertOne({Brand:[{CategoryName:"Mobile","Name":"Oppo"}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea3ea9b04263e90dac943e5") } > db.demo672.insertOne({Brand:[{CategoryName:"Mobile","Name":"Samsung"}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea3eaa404263e90dac943e6") } > db.demo672.insertOne({Brand:[{CategoryName:"Mobile","Name":"OnePlus"}]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea3eacc04263e90dac943e7") }

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

> db.demo672.find();

This will produce the following output −

{ "_id" : ObjectId("5ea3ea9b04263e90dac943e5"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "Oppo" } ] } { "_id" : ObjectId("5ea3eaa404263e90dac943e6"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "Samsung" } ] } { "_id" : ObjectId("5ea3eacc04263e90dac943e7"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "OnePlus" } ] }

Following is the query to fetch a specific document −

> db.demo672.find({"Brand.Name":"OnePlus"});

This will produce the following output −

{ "_id" : ObjectId("5ea3eacc04263e90dac943e7"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "OnePlus" } ] }
Updated on: 2020-05-13T09:58:05+05:30

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements