获得MongoDB中列的最高价值?
要获得MongoDB中列的最高值,可以将sort()与limit(1)一起使用。语法如下-
db.yourCollectionName.find().sort({"yourFieldName":-1}).limit(1);
为了理解上述语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.gettingHighestValueDemo.insertOne({"Value":1029}); { "acknowledged" : true, "insertedId" : ObjectId("5c900b885705caea966c5574") } > db.gettingHighestValueDemo.insertOne({"Value":3029}); { "acknowledged" : true, "insertedId" : ObjectId("5c900b8d5705caea966c5575") } > db.gettingHighestValueDemo.insertOne({"Value":1092}); { "acknowledged" : true, "insertedId" : ObjectId("5c900b925705caea966c5576") } > db.gettingHighestValueDemo.insertOne({"Value":18484}); { "acknowledged" : true, "insertedId" : ObjectId("5c900b955705caea966c5577") } > db.gettingHighestValueDemo.insertOne({"Value":37474}); { "acknowledged" : true, "insertedId" : ObjectId("5c900b9c5705caea966c5578") } > db.gettingHighestValueDemo.insertOne({"Value":88474}); { "acknowledged" : true, "insertedId" : ObjectId("5c900ba75705caea966c5579") } > db.gettingHighestValueDemo.insertOne({"Value":1938474}); { "acknowledged" : true, "insertedId" : ObjectId("5c900bab5705caea966c557a") }
在find()方法的帮助下显示集合中的所有文档。查询如下:
> db.gettingHighestValueDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c900b885705caea966c5574"), "Value" : 1029 } { "_id" : ObjectId("5c900b8d5705caea966c5575"), "Value" : 3029 } { "_id" : ObjectId("5c900b925705caea966c5576"), "Value" : 1092 } { "_id" : ObjectId("5c900b955705caea966c5577"), "Value" : 18484 } { "_id" : ObjectId("5c900b9c5705caea966c5578"), "Value" : 37474 } { "_id" : ObjectId("5c900ba75705caea966c5579"), "Value" : 88474 } { "_id" : ObjectId("5c900bab5705caea966c557a"), "Value" : 1938474 }
这是获取MongoDB中列的最大值的查询-
> db.gettingHighestValueDemo.find().sort({"Value":-1}).limit(1);
以下是显示最大值的输出-
{ "_id" : ObjectId("5c900bab5705caea966c557a"), "Value" : 1938474 }