使用aggregate()
排序,在MongoDB中使用$sort。让我们创建一个包含文档的集合-
> db.demo164.insertOne({"StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e36883d9e4f06af551997c8") } > db.demo164.insertOne({"StudentAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5e3688409e4f06af551997c9") } > db.demo164.insertOne({"StudentAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5e3688429e4f06af551997ca") } > db.demo164.insertOne({"StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e3688439e4f06af551997cb") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo164.find();
这将产生以下输出-
{ "_id" : ObjectId("5e36883d9e4f06af551997c8"), "StudentAge" : 24 } { "_id" : ObjectId("5e3688409e4f06af551997c9"), "StudentAge" : 25 } { "_id" : ObjectId("5e3688429e4f06af551997ca"), "StudentAge" : 22 } { "_id" : ObjectId("5e3688439e4f06af551997cb"), "StudentAge" : 21 }
这是使用MongoDB的查询aggregate()
-
> db.demo164.aggregate([{ $sort : { StudentAge : -1 } }]);
这将产生以下输出-
{ "_id" : ObjectId("5e3688409e4f06af551997c9"), "StudentAge" : 25 } { "_id" : ObjectId("5e36883d9e4f06af551997c8"), "StudentAge" : 24 } { "_id" : ObjectId("5e3688429e4f06af551997ca"), "StudentAge" : 22 } { "_id" : ObjectId("5e3688439e4f06af551997cb"), "StudentAge" : 21 }