本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$min
只有当指定值小于当前字段值时,$min更新运算符才会更新字段的值。此运算符对于在更新期间保持最小值很有用。
参数
-
field:要更新的字段。
-
value:要与当前字段值进行比较的值。
示例(MongoDB 外壳)
以下示例演示如何使用$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()