Fetch a specific document in MongoDB with array elements

MongoDBDatabaseBig Data Analytics

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" } ] }
raja
Published on 13-May-2020 13:27:20
Advertisements