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
Selected Reading
MongoDB aggregation framework to sort by length of array?
To sort by length of array, use aggregate(). Before that, get the count of records in an arrayusing $sum. Let us create a collection with documents
> db.demo33.insertOne({"ListOfStudent":["Chris","Bob"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e17556ccfb11e5c34d898ca")
}
> db.demo33.insertOne({"ListOfStudent":["David","Adam","Mike"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e17557acfb11e5c34d898cb")
}
> db.demo33.insertOne({"ListOfStudent":["Carol","Sam","John","Robert"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e1755a3cfb11e5c34d898cc")
}
Display all documents from a collection with the help of find() method −
> db.demo33.find();
This will produce the following output −
{ "_id" : ObjectId("5e17556ccfb11e5c34d898ca"), "ListOfStudent" : [ "Chris", "Bob" ] }
{ "_id" : ObjectId("5e17557acfb11e5c34d898cb"), "ListOfStudent" : [ "David", "Adam", "Mike" ] }
{ "_id" : ObjectId("5e1755a3cfb11e5c34d898cc"), "ListOfStudent" : [ "Carol", "Sam", "John", "Robert" ] }
Following is the query to sort by length of array −
> db.demo33.aggregate({$unwind:"$ListOfStudent"}, { $group : {_id:'$_id', ct:{$sum:1}}}, { $sort :{ ct: -1}} );
This will produce the following output −
{ "_id" : ObjectId("5e1755a3cfb11e5c34d898cc"), "ct" : 4 }
{ "_id" : ObjectId("5e17557acfb11e5c34d898cb"), "ct" : 3 }
{ "_id" : ObjectId("5e17556ccfb11e5c34d898ca"), "ct" : 2 } Advertisements
