Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } ] } }Advertisements