MongoDB 查詢如何找到某一列的最高數字值?


針對此目的,你可用 $not 運算子與 $type 結合使用。首先,使用文件建立一個集合:

> db.highestNumericValueOfAColumnDemo.insertOne(
...    {
...       "StudentName": "John",
...       "StudentMathMarks":69
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cba05727219729fde21ddb1")
}
> db.highestNumericValueOfAColumnDemo.insertOne(
...    {
...       "StudentName": "Carol",
...       "StudentMathMarks":"89"
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cba059d7219729fde21ddb2")
}
> db.highestNumericValueOfAColumnDemo.insertOne(
...    {
...       "StudentName": "Chris",
...       "StudentMathMarks":82
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cba059d7219729fde21ddb3")
}
> db.highestNumericValueOfAColumnDemo.insertOne(
...    {
...       "StudentName": "John",
...       "StudentMathMarks":"100"
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cba059d7219729fde21ddb4")
}

以下查詢可透過 find() 方法顯示集合中的所有文件:

> db.highestNumericValueOfAColumnDemo.find().pretty();

這將產生以下輸出:

{
   "_id" : ObjectId("5cba05727219729fde21ddb1"),
   "StudentName" : "John",
   "StudentMathMarks" : 69
}
{
   "_id" : ObjectId("5cba059d7219729fde21ddb2"),
   "StudentName" : "Carol",
   "StudentMathMarks" : "89"
}
{
   "_id" : ObjectId("5cba059d7219729fde21ddb3"),
   "StudentName" : "Chris",
   "StudentMathMarks" : 82
}
{
   "_id" : ObjectId("5cba059d7219729fde21ddb4"),
   "StudentName" : "John",
   "StudentMathMarks" : "100"
}

以下查詢用於找到某一列的最高數字值:

> db.highestNumericValueOfAColumnDemo.find({StudentMathMarks: {$not: {$type:
   2}}}).sort({StudentMathMarks: -1}).limit(1).pretty();

這將產生以下輸出:

{
   "_id" : ObjectId("5cba059d7219729fde21ddb3"),
   "StudentName" : "Chris",
   "StudentMathMarks" : 82
}

上述查詢忽略了字串值,因此我們僅獲得整數最高值,即 82。

更新日期:2020 年 7 月 2 日

瀏覽 145 次

開啟你的 職業生涯

完成課程以取得認證

立即開始
廣告
© . All rights reserved.