要按Array值对MongoDB集合进行排序,请使用aggregate()和$sort。让我们创建一个包含文档的集合-
> db.demo577.insertOne( ... { ... ... "student": { ... "details": [ ... { ... Name:"Chris", ... Score:45 ... }, ... { ... Name:"Bob", ... Score:33 ... }, ... { ... Name:"David", ... Score:48 ... } ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e916ff1581e9acd78b427ff") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo577.find();
这将产生以下输出-
{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : [ { "Name" : "Chris", "Score" : 45 }, { "Name" : "Bob", "Score" : 33 }, { "Name" : "David", "Score" : 48 } ] } }
以下是按数组值对集合进行排序的查询-
> db.demo577.aggregate([ ... {$unwind:"$student"}, ... {$unwind:"$student.details"}, ... ... {$sort:{"student.details.Score":-1}} ... ]);
这将产生以下输出-
{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "David", "Score" : 48 } } } { "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "Chris", "Score" : 45 } } } { "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "Bob", "Score" : 33 } } }