
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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" ] } ] }
- Related Questions & Answers
- MongoDB query for Partial Object in an array
- MongoDB query to find data from an array inside an object?
- MongoDB query to remove empty objects in an object-array?
- Query on the last object of an array with MongoDB
- MongoDB query to replace value in an array?
- MongoDB query to change simple field into an object?
- MongoDB query to push document into an array
- MongoDB query to update an array using FindAndUpdate()?
- How to insert an item to an array that is inside an object in MongoDB?
- MongoDB query to return specific fields from an array?
- Query to retrieve multiple items in an array in MongoDB?
- How to access an object through another object in JavaScript?
- MongoDB query to set a sub item in an array?
- Query an array in MongoDB to fetch a specific value
- How to get items from an object array in MongoDB?
Advertisements