如何在 MongoDB 中按子文档排序、选择和查询?
若要排序,在 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 }
广告