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
Write a MongoDB query to get nested value?
You can use dot notation to get nested value. Let us first create a collection with documents
> db.nestedQueryDemo.insertOne(
... {
...
... "EmployeeName" : "John",
... "EmployeeDetails" :
... {
...
... "_id":"EMP-101",
... "EmployeeAge":23,
... "EmployeeCompanyName":"IBM"
...
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ea31dd628fa4220163b69")
}
> db.nestedQueryDemo.insertOne(
... {
...
... "EmployeeName" : "Carol",
... "EmployeeDetails" :
... {
...
... "_id":"EMP-110",
... "EmployeeAge":29,
... "EmployeeCompanyName":"Amazon"
...
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9ea36bd628fa4220163b6a")
}
Following is the query to display all documents from a collection with the help of find() method
> db.nestedQueryDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5c9ea31dd628fa4220163b69"),
"EmployeeName" : "John",
"EmployeeDetails" : {
"_id" : "EMP-101",
"EmployeeAge" : 23,
"EmployeeCompanyName" : "IBM"
}
}
{
"_id" : ObjectId("5c9ea36bd628fa4220163b6a"),
"EmployeeName" : "Carol",
"EmployeeDetails" : {
"_id" : "EMP-110",
"EmployeeAge" : 29,
"EmployeeCompanyName" : "Amazon"
}
}
Following is the query for MongoDB nested value query
> db.nestedQueryDemo.find({"EmployeeDetails._id":"EMP-110"}).pretty();
This will produce the following output
{
"_id" : ObjectId("5c9ea36bd628fa4220163b6a"),
"EmployeeName" : "Carol",
"EmployeeDetails" : {
"_id" : "EMP-110",
"EmployeeAge" : 29,
"EmployeeCompanyName" : "Amazon"
}
}Advertisements