MongoDB 查询如何对嵌套数组进行排序?
要在 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 } ] }
广告