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
Querying an array of arrays in MongoDB?
Use the $elemMatch operator with nested $in to query an array of arrays in MongoDB. This approach allows you to search for specific values within nested array structures.
Syntax
db.collection.find({
"arrayField": {
$elemMatch: {
$elemMatch: {
$in: ["searchValue"]
}
}
}
});
Sample Data
db.arrayOfArraysDemo.insertMany([
{
"EmployeeName": "Larry",
"EmployeeSkills": [["Java", "MongoDB", "MySQL", "SQL Server"]]
},
{
"EmployeeName": "Mike",
"EmployeeSkills": [["C", "C++"]]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c7f7a8d8d10a061296a3c5b"),
ObjectId("5c7f7aa68d10a061296a3c5c")
]
}
Display All Documents
db.arrayOfArraysDemo.find().pretty();
{
"_id": ObjectId("5c7f7a8d8d10a061296a3c5b"),
"EmployeeName": "Larry",
"EmployeeSkills": [
[
"Java",
"MongoDB",
"MySQL",
"SQL Server"
]
]
}
{
"_id": ObjectId("5c7f7aa68d10a061296a3c5c"),
"EmployeeName": "Mike",
"EmployeeSkills": [
[
"C",
"C++"
]
]
}
Example: Query Array of Arrays
Find employees who have "MongoDB" as a skill in their nested array structure ?
db.arrayOfArraysDemo.find({
'EmployeeSkills': {
$elemMatch: {
$elemMatch: {
$in: ['MongoDB']
}
}
}
}).pretty();
{
"_id": ObjectId("5c7f7a8d8d10a061296a3c5b"),
"EmployeeName": "Larry",
"EmployeeSkills": [
[
"Java",
"MongoDB",
"MySQL",
"SQL Server"
]
]
}
How It Works
- The outer
$elemMatchmatches elements in the main array (EmployeeSkills) - The inner
$elemMatchmatches elements in the nested array -
$insearches for the specified value within those nested elements
Conclusion
Use nested $elemMatch operators with $in to effectively query array of arrays in MongoDB. This pattern handles multi-level array structures and finds documents containing specific values in nested arrays.
Advertisements
