本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$inc
该$inc运算符用于将字段的值增加指定量。它用于更新数值字段,例如计数器或评级,而无需检索当前值、计算新值然后更新该字段。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$inc运算符来增加文档的age字段。
创建示例文档
db.users.insertOne({_id: 123, name: "John Doe", age: 30})
查询示例
db.users.updateOne({_id: 123}, {$inc: {age: 1}})
查看更新的文档
db.users.findOne({_id: 123})
输出
{ "_id" : 123, "name" : "John Doe", "age" : 31 }
代码示例
要查看使用该$inc命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function updateWithInc() {
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('users');
const result = await collection.updateOne(
{ _id: 123 },
{ $inc: { age: 1 } }
);
console.log(result);
await client.close();
}
updateWithInc();
- Python
-
from pymongo import MongoClient
def update_with_inc():
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['users']
result = collection.update_one(
{'_id': 123},
{'$inc': {'age': 1}}
)
print(result.modified_count)
client.close()
update_with_inc()