How do I display a list of objects based on a specific property with MongoDB?


To display a list of objects based on a specific property, use dot notation in find(). Let us create a collection with documents −

> db.demo455.insertOne({"Information":{"Student":[{"Name":"Chris","Age":22}]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7e1876dbcb9adb296c95c5")
}
> db.demo455.insertOne({"Information":{"Student":[{"Name":"David","Age":21}]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7e1883dbcb9adb296c95c6")
}
> db.demo455.insertOne({"Information":{"Student":[{"Name":"Bob","Age":24}]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7e188adbcb9adb296c95c7")
}
> db.demo455.insertOne({"Information":{"Student":[{"Name":"Robert","Age":21}]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7e18bcdbcb9adb296c95c8")
}

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

> db.demo455.find();

This will produce the following output −

{ "_id" : ObjectId("5e7e1876dbcb9adb296c95c5"), "Information" : { "Student" : [ { "Name" :
"Chris", "Age" : 22 } ] } }
{ "_id" : ObjectId("5e7e1883dbcb9adb296c95c6"), "Information" : { "Student" : [ { "Name" :
"David", "Age" : 21 } ] } }
{ "_id" : ObjectId("5e7e188adbcb9adb296c95c7"), "Information" : { "Student" : [ { "Name" :
"Bob", "Age" : 24 } ] } }
{ "_id" : ObjectId("5e7e18bcdbcb9adb296c95c8"), "Information" : { "Student" : [ { "Name" :
"Robert", "Age" : 21 } ] } }

Following is the query to display a list of objects based on a specific property −

> db.demo455.find({"Information.Student.Age":21});

This will produce the following output −

{ "_id" : ObjectId("5e7e1883dbcb9adb296c95c6"), "Information" : { "Student" : [ { "Name" :
"David", "Age" : 21 } ] } }
{ "_id" : ObjectId("5e7e18bcdbcb9adb296c95c8"), "Information" : { "Student" : [ { "Name" :
"Robert", "Age" : 21 } ] } }

Updated on: 11-May-2020

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements