 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
MongoDB query to access an object in an array
To access an object in an array, use dot notation. Let us create a collection with documents −
> db.demo299.insertOne( ...   { ...      "id":100, ...      "Name":"Robert", ...      "details":[ ...         { ...            "SubjectName":["C++","Python"] ...         }, ...         { ...            "SubjectName":["Spring","Hibernate"] ...         } ...      ] ...   } ...); {    "acknowledged" : true,    "insertedId" : ObjectId("5e4d685a5d93261e4bc9ea4b") } > > > db.demo299.insertOne( ...   { ...      "id":101, ...      "Name":"Adam", ...      "details":[ ...         { ...            "SubjectName":["Python","JSP"] ...         }, ...         { ...            "SubjectName":["Servlet","Operating System"] ...         } ...      ] ...   } ...); {    "acknowledged" : true,    "insertedId" : ObjectId("5e4d685b5d93261e4bc9ea4c") } Display all documents from a collection with the help of find() method −
> db.demo299.find();
This will produce the following output −
{    "_id" : ObjectId("5e4d685a5d93261e4bc9ea4b"), "id" : 100, "Name" : "Robert", "details" : [       { "SubjectName" : [ "C++", "Python" ] },       { "SubjectName" : [ "Spring", "Hibernate" ] }    ] } {    "_id" : ObjectId("5e4d685b5d93261e4bc9ea4c"), "id" : 101, "Name" : "Adam", "details" : [       { "SubjectName" : [ "Python", "JSP" ] }, { "SubjectName" : [ "Servlet", "Operating System" ] }    ] } Following is the query to access an object in an array −
> db.demo299.find({"details.SubjectName":"Servlet"}); This will produce the following output −
{    "_id" : ObjectId("5e4d685b5d93261e4bc9ea4c"), "id" : 101, "Name" : "Adam", "details" : [       { "SubjectName" : [ "Python", "JSP" ] }, { "SubjectName" : [ "Servlet", "Operating System" ] }    ] }Advertisements
 