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
MongoDB query to find data from an array inside an object?
Let us first create a collection with documents −
> db.findDataDemo.insertOne(
{
"_id": new ObjectId(),
"CustomerName":"John",
"CustomerDetails" : {
"CountryName" : [
"AUS"
],
"isMarried" : [
false
]
}
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cefa5eeef71edecf6a1f6a5")
}
> db.findDataDemo.insertOne(
{
"_id": new ObjectId(),
"CustomerName":"Carol",
"CustomerDetails" : {
"CountryName" : [
"UK"
],
"isMarried" : [
true
]
}
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cefa60aef71edecf6a1f6a6")
}
Display all documents from a collection with the help of find() method −
> db.findDataDemo.find().pretty();
Output
{
"_id" : ObjectId("5cefa5eeef71edecf6a1f6a5"),
"CustomerName" : "John",
"CustomerDetails" : {
"CountryName" : [
"AUS"
],
"isMarried" : [
false
]
}
}
{
"_id" : ObjectId("5cefa60aef71edecf6a1f6a6"),
"CustomerName" : "Carol",
"CustomerDetails" : {
"CountryName" : [
"UK"
],
"isMarried" : [
true
]
}
}
Following is the query to find data from an array inside an object −
> db.findDataDemo.find({"CustomerDetails.CountryName":"UK"});
Output
{ "_id" : ObjectId("5cefa60aef71edecf6a1f6a6"), "CustomerName" : "Carol", "CustomerDetails" : { "CountryName" : [ "UK" ], "isMarried" : [ true ] } }Advertisements