- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 fetch array values
Use find() along with $elemMatch to fetch array values. Let us first create a collection with documents −
> db.fetchingArrayValuesDemo.insertOne( ... { ... "StudentName": "David", ... "StudentDetails": [ ... { ... "FatherName": "Bob", ... "CountryName": "US", ... ... "Favourite": [ ... { ... "Teacher": "DAVID", ... "Subject": [ ... "MySQL", ... "MongoDB", ... "Java" ... ], ... "Marks": [ ... 50, ... 60, ... 65 ... ] ... } ... ] ... ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e06fc3425ddae1f53b621fa") } > db.fetchingArrayValuesDemo.insertOne( ... { ... "StudentName": "Robert", ... "StudentDetails": [ ... { ... "FatherName": "Sam", ... "CountryName": "AUS", ... ... "Favourite": [ ... { ... "Teacher": "MIKE", ... "Subject": [ ... "Python", ... "C", ... "C++" ... ], ... "Marks": [ ... 76, ... 89, ... 91 ... ] ... } ... ] ... ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e06fc6825ddae1f53b621fb") }
Following is the query to display all documents from a collection with the help of find() method −
> db.fetchingArrayValuesDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5e06fc3425ddae1f53b621fa"), "StudentName" : "David", "StudentDetails" : [ { "FatherName" : "Bob", "CountryName" : "US", "Favourite" : [ { "Teacher" : "DAVID", "Subject" : [ "MySQL", "MongoDB", "Java" ], "Marks" : [ 50, 60, 65 ] } ] } ] } { "_id" : ObjectId("5e06fc6825ddae1f53b621fb"), "StudentName" : "Robert", "StudentDetails" : [ { "FatherName" : "Sam", "CountryName" : "AUS", "Favourite" : [ { "Teacher" : "MIKE", "Subject" : [ "Python", "C", "C++" ], "Marks" : [ 76, 89, 91 ] } ] } ] }
Here is the query to fetch array values −
> db.fetchingArrayValuesDemo.find({ ... StudentDetails:{ ... $elemMatch: { ... Favourite: { ... $elemMatch: { ... Teacher: "DAVID" ... } ... } ... } ... } ... });
This will produce the following output −
{ "_id" : ObjectId("5e06fc3425ddae1f53b621fa"), "StudentName" : "David", "StudentDetails" : [ { "FatherName" : "Bob", "CountryName" : "US", "Favourite" : [ { "Teacher" : "DAVID", "Subject" : [ "MySQL", "MongoDB", "Java" ], "Marks" : [ 50, 60, 65 ] } ] } ] }
Advertisements