本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$min
只有在指定的值小於目前的欄位值時,$min更新運算子才會更新欄位的值。此運算子有助於跨更新維持最小值。
參數
-
field:要更新的欄位。
-
value:要與目前欄位值比較的值。
範例 (MongoDB Shell)
下列範例示範如何使用 $min 運算子更新氣象站的最低記錄溫度。
建立範例文件
db.weather.insertMany([
{ _id: 1, station: "Station A", lowestTemp: 15 },
{ _id: 2, station: "Station B", lowestTemp: 20 },
{ _id: 3, station: "Station C", lowestTemp: 18 }
])
更新範例
db.weather.updateOne(
{ _id: 1 },
{ $min: { lowestTemp: 12 } }
)
結果
工作站 A lowestTemp的欄位會更新為 12,因為 12 小於目前值 15。
{ "_id": 1, "station": "Station A", "lowestTemp": 12 }
程式碼範例
若要檢視使用 $min命令的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const collection = db.collection('weather');
const result = await collection.updateOne(
{ _id: 1 },
{ $min: { lowestTemp: 12 } }
);
console.log(result);
await client.close();
}
example();
- Python
-
from pymongo import MongoClient
def example():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['weather']
result = collection.update_one(
{ '_id': 1 },
{ '$min': { 'lowestTemp': 12 } }
)
print(result)
client.close()
example()