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
Easiest way to sort an array in MongoDB
The easiest way to sort an array in MongoDB is to use the aggregation pipeline with $unwind, $sort, and $group operators. This approach unwraps the array, sorts the elements, and reconstructs the document.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $sort: { "arrayField.sortField": 1 } },
{ $group: { _id: "$_id", arrayField: { $push: "$arrayField" } } }
]);
Sample Data
db.demo242.insertOne({
"details2": [
{ "ShipingDate": new ISODate("2019-10-11"), "Price": 1400 },
{ "ShipingDate": new ISODate("2019-10-01"), "Price": 1600 }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e4429229af932883c61ea44")
}
Display Original Document
db.demo242.find();
{
"_id": ObjectId("5e4429229af932883c61ea44"),
"details2": [
{ "ShipingDate": ISODate("2019-10-11T00:00:00Z"), "Price": 1400 },
{ "ShipingDate": ISODate("2019-10-01T00:00:00Z"), "Price": 1600 }
]
}
Sort Array by Date (Ascending)
db.demo242.aggregate([
{ $unwind: "$details2" },
{ $sort: { "details2.ShipingDate": 1 } },
{ $group: { _id: "$_id", details2: { $push: "$details2" } } }
]);
{
"_id": ObjectId("5e4429229af932883c61ea44"),
"details2": [
{ "ShipingDate": ISODate("2019-10-01T00:00:00Z"), "Price": 1600 },
{ "ShipingDate": ISODate("2019-10-11T00:00:00Z"), "Price": 1400 }
]
}
How It Works
-
$unwinddeconstructs the array into separate documents -
$sortsorts the unwound documents by the specified field -
$groupreconstructs the document with$pushto rebuild the sorted array
Conclusion
Use the aggregation pipeline with $unwind, $sort, and $group to sort arrays in MongoDB. This three-stage approach provides complete control over array sorting while preserving document structure.
Advertisements
