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
Is it possible to achieve a slice chain in MongoDB?
Yes, you can achieve slice chaining in MongoDB using the aggregation framework. The $unwind operator can be applied multiple times to flatten nested arrays, allowing you to access and manipulate deeply nested elements.
Syntax
db.collection.aggregate([
{ $match: { "field": "value" } },
{ $unwind: "$arrayField" },
{ $unwind: "$arrayField" },
{ $group: { "_id": "$field", "result": { $last: "$arrayField" } } }
]);
Sample Data
db.sliceOfSliceDemo.insertOne({
"Name": "John",
"Details": [["First 1:1", "First 1:2"], ["second 2:1", "Second 2:2"]]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ccf3fcfdceb9a92e6aa195a")
}
View Sample Data
db.sliceOfSliceDemo.find().pretty();
{
"_id": ObjectId("5ccf3fcfdceb9a92e6aa195a"),
"Name": "John",
"Details": [
[
"First 1:1",
"First 1:2"
],
[
"second 2:1",
"Second 2:2"
]
]
}
Example: Slice Chain Implementation
To get the last element from the nested array structure, use double $unwind to flatten both array levels ?
db.sliceOfSliceDemo.aggregate([
{ $match: { "Name": "John" } },
{ $unwind: "$Details" },
{ $unwind: "$Details" },
{ $group: { "_id": "$Name", "Details": { $last: "$Details" } } },
{ $project: { "Name": "$_id", "Details": 1 } }
]);
{ "_id": "John", "Details": "Second 2:2", "Name": "John" }
How It Works
- First $unwind ? Flattens the outer array, creating separate documents for each sub-array
- Second $unwind ? Flattens the inner arrays, creating documents for each string element
- $group with $last ? Retrieves the final element after all unwinding operations
Conclusion
Slice chaining in MongoDB is achieved through multiple $unwind operations in the aggregation pipeline. This technique allows you to access deeply nested array elements and perform complex data transformations on multi-dimensional array structures.
Advertisements
