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