按照数组值对 MongoDB 收藏分类?
要按照数组值对 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 } } }
广告