要按数组长度排序,请使用aggregate()
。在此之前,使用$sum获取数组中的记录数。让我们创建包含文档的集合
> 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") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo33.find();
这将产生以下输出-
{ "_id" : ObjectId("5e17556ccfb11e5c34d898ca"), "ListOfStudent" : [ "Chris", "Bob" ] } { "_id" : ObjectId("5e17557acfb11e5c34d898cb"), "ListOfStudent" : [ "David", "Adam", "Mike" ] } { "_id" : ObjectId("5e1755a3cfb11e5c34d898cc"), "ListOfStudent" : [ "Carol", "Sam", "John", "Robert" ] }
以下是按数组长度排序的查询-
> 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 }