对于降序,请使用-1,它指定sort()的排序顺序,让我们创建一个包含文档的集合-
> db.demo267.insertOne({id:100,"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4811951627c0c63e7dbaab") } > db.demo267.insertOne({id:100,"Name":"Adam"}); { "acknowledged" : true, "insertedId" : ObjectId("5e48119e1627c0c63e7dbaac") } > db.demo267.insertOne({id:100,"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4811a51627c0c63e7dbaad") } > db.demo267.insertOne({id:100,"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4811ab1627c0c63e7dbaae") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo267.find().pretty(); { "_id" : ObjectId("5e4811951627c0c63e7dbaab"), "id" : 100, "Name" : "Chris" } { "_id" : ObjectId("5e48119e1627c0c63e7dbaac"), "id" : 100, "Name" : "Adam" } { "_id" : ObjectId("5e4811a51627c0c63e7dbaad"), "id" : 100, "Name" : "David" } { "_id" : ObjectId("5e4811ab1627c0c63e7dbaae"), "id" : 100, "Name" : "Bob" }
在find()方法的帮助下显示集合中的所有文档-
> db.demo267.find().sort({Name:-1}).limit(1);
这将产生以下输出-
{ "_id" : ObjectId("5e4811a51627c0c63e7dbaad"), "id" : 100, "Name" : "David" }