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 framework to sort by length of array?
To sort documents by the length of an array field in MongoDB, use the aggregation framework with $addFields and $size operators to calculate array lengths, then sort by the computed field.
Syntax
db.collection.aggregate([
{ $addFields: { arrayLength: { $size: "$arrayField" } } },
{ $sort: { arrayLength: -1 } }
]);
Sample Data
db.demo33.insertMany([
{ "ListOfStudent": ["Chris", "Bob"] },
{ "ListOfStudent": ["David", "Adam", "Mike"] },
{ "ListOfStudent": ["Carol", "Sam", "John", "Robert"] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e17556ccfb11e5c34d898ca"),
ObjectId("5e17557acfb11e5c34d898cb"),
ObjectId("5e1755a3cfb11e5c34d898cc")
]
}
Display Sample Data
db.demo33.find();
{ "_id": ObjectId("5e17556ccfb11e5c34d898ca"), "ListOfStudent": ["Chris", "Bob"] }
{ "_id": ObjectId("5e17557acfb11e5c34d898cb"), "ListOfStudent": ["David", "Adam", "Mike"] }
{ "_id": ObjectId("5e1755a3cfb11e5c34d898cc"), "ListOfStudent": ["Carol", "Sam", "John", "Robert"] }
Method 1: Using $size (Recommended)
Sort documents by array length in descending order using $size to calculate array length ?
db.demo33.aggregate([
{ $addFields: { studentCount: { $size: "$ListOfStudent" } } },
{ $sort: { studentCount: -1 } }
]);
{ "_id": ObjectId("5e1755a3cfb11e5c34d898cc"), "ListOfStudent": ["Carol", "Sam", "John", "Robert"], "studentCount": 4 }
{ "_id": ObjectId("5e17557acfb11e5c34d898cb"), "ListOfStudent": ["David", "Adam", "Mike"], "studentCount": 3 }
{ "_id": ObjectId("5e17556ccfb11e5c34d898ca"), "ListOfStudent": ["Chris", "Bob"], "studentCount": 2 }
Method 2: Using $unwind and $group
Alternative approach using $unwind to deconstruct array and $group to count elements ?
db.demo33.aggregate([
{ $unwind: "$ListOfStudent" },
{ $group: { _id: "$_id", ct: { $sum: 1 } } },
{ $sort: { ct: -1 } }
]);
{ "_id": ObjectId("5e1755a3cfb11e5c34d898cc"), "ct": 4 }
{ "_id": ObjectId("5e17557acfb11e5c34d898cb"), "ct": 3 }
{ "_id": ObjectId("5e17556ccfb11e5c34d898ca"), "ct": 2 }
Key Differences
- $size method: Preserves original document structure and adds array length field
- $unwind method: Returns only document ID and count, losing original array data
-
$sizeis more efficient for simple length-based sorting
Conclusion
Use $size with $addFields to sort by array length while preserving document structure. The $unwind approach works but loses original data, making $size the preferred method for most use cases.
Advertisements
