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
Sort array in MongoDB query and project all fields?
To sort an array within a document and project all fields in MongoDB, use the aggregation pipeline with $unwind, $sort, $group, and $project stages.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $sort: { "arrayField.field": 1 } },
{ $group: { _id: "$_id", arrayField: { $push: "$arrayField" } } },
{ $project: { _id: 1, arrayField: 1 } }
]);
Sample Data
db.demo252.insertOne({
"Values": [
{ "v1": 20, "v2": 30 },
{ "v1": 20, "v2": 20 },
{ "v1": 10, "v2": 7 }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e46c2761627c0c63e7dba78")
}
Display the document to verify the data:
db.demo252.find();
{ "_id": ObjectId("5e46c2761627c0c63e7dba78"), "Values": [ { "v1": 20, "v2": 30 }, { "v1": 20, "v2": 20 }, { "v1": 10, "v2": 7 } ] }
Example: Sort Array by Multiple Fields
Sort the Values array first by v2 in ascending order, then by v1 in ascending order:
db.demo252.aggregate([
{ $unwind: "$Values" },
{ $sort: { "Values.v2": 1, "Values.v1": 1 } },
{ $group: {
"_id": "$_id",
"Values": { $push: "$Values" }
}},
{ $project: {
"_id": 1,
"Values": 1
}}
]);
{ "_id": ObjectId("5e46c2761627c0c63e7dba78"), "Values": [ { "v1": 10, "v2": 7 }, { "v1": 20, "v2": 20 }, { "v1": 20, "v2": 30 } ] }
How It Works
-
$unwindcreates separate documents for each array element -
$sortorders the unwound documents by specified fields -
$groupreconstructs the array using$push -
$projectshapes the final output to include all desired fields
Conclusion
The aggregation pipeline effectively sorts arrays within documents while preserving all fields. This approach maintains document structure and provides flexible sorting options for complex array operations.
Advertisements
