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
MongoDB Aggregation to slice array inside array
To slice an array inside another array in MongoDB, use the aggregate() method with $addFields, $map, and $slice operators. This allows you to limit the number of elements returned from nested arrays.
Syntax
db.collection.aggregate([
{ $addFields: {
"arrayField": {
$map: {
"input": "$arrayField",
"as": "element",
"in": {
"field1": "$$element.field1",
"nestedArray": { $slice: [ "$$element.nestedArray", count ] }
}
}
}
}}
]);
Sample Data
db.demo111.insertOne({
"_id": 101,
"Name": "Chris",
"Details": [
{
"_id": 101,
"Score": 78,
"Subjects": [
{
"_id": "10001",
"SubjectName": "MySQL"
},
{
"_id": "10003",
"SubjectName": "MongoDB"
}
]
},
{
"_id": 102,
"Score": 87,
"Subjects": [
{
"_id": "10004",
"SubjectName": "Java"
}
]
}
]
});
{ "acknowledged": true, "insertedId": 101 }
Example: Slice First Element from Subjects Array
To limit each Subjects array to only the first element, use $slice with count 1 ?
db.demo111.aggregate([
{ $addFields: {
"Details": {
$map: {
"input": "$Details",
"as": "out",
"in": {
"_id": "$$out._id",
"Score": "$$out.Score",
"Subjects": { $slice: [ "$$out.Subjects", 1 ] }
}
}
}
}}
]);
{
"_id": 101,
"Name": "Chris",
"Details": [
{ "_id": 101, "Score": 78, "Subjects": [ { "_id": "10001", "SubjectName": "MySQL" } ] },
{ "_id": 102, "Score": 87, "Subjects": [ { "_id": "10004", "SubjectName": "Java" } ] }
]
}
Key Points
-
$mapiterates through each element in the outer Details array -
$slicelimits the number of elements returned from the nested Subjects array - Use
$$elementto reference fields within the mapped element
Conclusion
Combine $addFields, $map, and $slice to effectively slice arrays within arrays. The $map operator processes each outer array element, while $slice controls the number of nested array elements returned.
Advertisements
