要进行排序,请在MongoDB中使用$sort。让我们创建一个包含文档的集合-
> db.demo236.insertOne({"details":{"Name":"Chris","Age":21}}); { "acknowledged" : true, "insertedId" : ObjectId("5e419015f4cebbeaebec514c") } > db.demo236.insertOne({"details":{"Name":"David","Age":23}}); { "acknowledged" : true, "insertedId" : ObjectId("5e41901cf4cebbeaebec514d") } > db.demo236.insertOne({"details":{"Name":"Bob","Age":24}}); { "acknowledged" : true, "insertedId" : ObjectId("5e419023f4cebbeaebec514e") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo236.find();
这将产生以下输出-
{ "_id" : ObjectId("5e419015f4cebbeaebec514c"), "details" : { "Name" : "Chris", "Age" : 21 } } { "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "details" : { "Name" : "David", "Age" : 23 } } { "_id" : ObjectId("5e419023f4cebbeaebec514e"), "details" : { "Name" : "Bob", "Age" : 24 } }
以下是对MongoDB中的子文档进行排序,选择和查询的查询-
> db.demo236.aggregate( ... [ ... { $unwind: "$details" }, ... { $project: { ... Name: '$details.Name', ... Age: '$details.Age' ... ... }}, ... { $sort: {Name: -1}} ...] ...);
这将产生以下输出-
{ "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "Name" : "David", "Age" : 23 } { "_id" : ObjectId("5e419015f4cebbeaebec514c"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e419023f4cebbeaebec514e"), "Name" : "Bob", "Age" : 24 }