要从集合中获取最大元素,请按具有限制的降序排列。让我们创建一个包含文档的集合-
> > db.demo669.insertOne({"Marks":76}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3133c04263e90dac943d9") } > db.demo669.insertOne({"Marks":55}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3133f04263e90dac943da") } > db.demo669.insertOne({"Marks":89}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3134204263e90dac943db") } > db.demo669.insertOne({"Marks":88}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3134504263e90dac943dc") } > db.demo669.insertOne({"Marks":79}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3134e04263e90dac943dd") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo669.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea3133c04263e90dac943d9"), "Marks" : 76 } { "_id" : ObjectId("5ea3133f04263e90dac943da"), "Marks" : 55 } { "_id" : ObjectId("5ea3134204263e90dac943db"), "Marks" : 89 } { "_id" : ObjectId("5ea3134504263e90dac943dc"), "Marks" : 88 } { "_id" : ObjectId("5ea3134e04263e90dac943dd"), "Marks" : 79 }
以下是从集合中获取最大元素的查询-
> db.demo669.find().sort({"Marks":-1}).limit(1);
这将产生以下输出-
{ "_id" : ObjectId("5ea3134204263e90dac943db"), "Marks" : 89 }