Using object as key for finding values in MongoDB


For finding values, use find() in MongoDB. Under that, use dot notation. Let us create a collection with documents −

> db.demo361.insertOne({"details":{"FirstName":"Chris","LastName":"Brown"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a61f54a481fef8ec7a19")
}
> db.demo361.insertOne({"details":{"FirstName":"David","LastName":"Miller"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a62854a481fef8ec7a1a")
}
> db.demo361.insertOne({"details":{"FirstName":"John","LastName":"Doe"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a63654a481fef8ec7a1b")
}

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

> db.demo361.find();

This will produce the following output −

{ "_id" : ObjectId("5e56a61f54a481fef8ec7a19"), "details" : { "FirstName" : "Chris", "LastName" : "Brown" } }
{ "_id" : ObjectId("5e56a62854a481fef8ec7a1a"), "details" : { "FirstName" : "David", "LastName" : "Miller" } }
{ "_id" : ObjectId("5e56a63654a481fef8ec7a1b"), "details" : { "FirstName" : "John", "LastName" : "Doe" } }

Following is the query to use an object as key for finding values −

> db.demo361.find({},{"details.LastName":1});

This will produce the following output −

{ "_id" : ObjectId("5e56a61f54a481fef8ec7a19"), "details" : { "LastName" : "Brown" } }
{ "_id" : ObjectId("5e56a62854a481fef8ec7a1a"), "details" : { "LastName" : "Miller" } }
{ "_id" : ObjectId("5e56a63654a481fef8ec7a1b"), "details" : { "LastName" : "Doe" } }

Updated on: 02-Apr-2020

968 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements