Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Query array of nested string with MongoDB?
To query array of nested string in MongoDB, you can use dot notation to access nested array elements. This allows you to search for specific string values within arrays that are nested inside other objects.
Syntax
db.collection.find({"parentField.nestedArrayField": "searchValue"})
Sample Data
Let us first create a collection with documents containing nested arrays of strings ?
db.nestedStringDemo.insertMany([
{
"CustomerName": "John",
"CustomerOtherDetails": [
{ "Age": 29, "CountryName": "US" },
{
"CompanyName": "Amazon",
"Salary": 150000,
"ProjectName": ["Online Library Management System", "Pig Dice Game"]
}
]
},
{
"CustomerName": "Chris",
"CustomerOtherDetails": [
{ "Age": 27, "CountryName": "AUS" },
{
"CompanyName": "Google",
"Salary": 250000,
"ProjectName": ["Chat Application", "Game Design"]
}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cea4629ef71edecf6a1f690"),
ObjectId("5cea466eef71edecf6a1f691")
]
}
Display All Documents
db.nestedStringDemo.find().pretty();
{
"_id": ObjectId("5cea4629ef71edecf6a1f690"),
"CustomerName": "John",
"CustomerOtherDetails": [
{
"Age": 29,
"CountryName": "US"
},
{
"CompanyName": "Amazon",
"Salary": 150000,
"ProjectName": [
"Online Library Management System",
"Pig Dice Game"
]
}
]
}
{
"_id": ObjectId("5cea466eef71edecf6a1f691"),
"CustomerName": "Chris",
"CustomerOtherDetails": [
{
"Age": 27,
"CountryName": "AUS"
},
{
"CompanyName": "Google",
"Salary": 250000,
"ProjectName": [
"Chat Application",
"Game Design"
]
}
]
}
Query Array of Nested Strings
Now, let us query an array of nested string using dot notation to find documents where ProjectName contains "Chat Application" ?
db.nestedStringDemo.find({"CustomerOtherDetails.ProjectName": "Chat Application"}).pretty();
{
"_id": ObjectId("5cea466eef71edecf6a1f691"),
"CustomerName": "Chris",
"CustomerOtherDetails": [
{
"Age": 27,
"CountryName": "AUS"
},
{
"CompanyName": "Google",
"Salary": 250000,
"ProjectName": [
"Chat Application",
"Game Design"
]
}
]
}
Conclusion
Use dot notation with the format parentField.nestedArrayField to query nested string arrays in MongoDB. This automatically searches through array elements to find matching values within the nested structure.
Advertisements
