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
Set filtering conditions for nested array in MongoDB
To set filtering conditions for nested arrays in MongoDB, use the $filter operator combined with $anyElementTrue and $map in an aggregation pipeline. This approach allows you to filter outer array elements based on conditions within deeply nested arrays.
Syntax
db.collection.aggregate([
{
$addFields: {
"arrayField": {
$filter: {
input: "$arrayField",
as: "element",
cond: {
$anyElementTrue: {
$map: {
input: "$$element.nestedArray",
in: { condition_expression }
}
}
}
}
}
}
}
]);
Sample Data
db.demo725.insertOne({
"details": {
"userMessages": [
{
"Messages": [
{ "Message": "Hello" },
{ "Message": "How" },
{ "Message": "are" }
]
},
{
"Messages": [
{ "Message": "Good" },
{ "Message": "Bye" }
]
},
{
"Messages": [
{ "Message": "Hello" },
{ "Message": "Bye" }
]
}
]
}
});
Example: Filter Messages Containing "Hello"
Filter userMessages array to keep only elements that contain "Hello" in any of their nested Messages ?
db.demo725.aggregate([
{
$addFields: {
"details.userMessages": {
$filter: {
input: "$details.userMessages",
as: "out",
cond: {
$anyElementTrue: {
$map: {
input: "$$out.Messages",
in: { $gte: [ { $indexOfBytes: [ "$$this.Message", "Hello" ] }, 0 ] }
}
}
}
}
}
}
}
]);
{
"_id" : ObjectId("5eab16cd43417811278f5893"),
"details" : {
"userMessages" : [
{
"Messages" : [
{ "Message" : "Hello" },
{ "Message" : "How" },
{ "Message" : "are" }
]
},
{
"Messages" : [
{ "Message" : "Hello" },
{ "Message" : "Bye" }
]
}
]
}
}
How It Works
-
$filterevaluates each element in the outer array against a condition -
$maptransforms each nested array element to check the condition -
$anyElementTruereturns true if any nested element meets the criteria -
$indexOfBytessearches for "Hello" substring, returning -1 if not found
Conclusion
Combining $filter, $map, and $anyElementTrue enables complex filtering of nested arrays based on conditions within deeply nested elements. This pattern is essential for working with multi-level document structures in MongoDB.
Advertisements
