$inc - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$inc

$inc 演算子は、フィールドの値を指定された量だけ増分するために使用されます。カウンターやレーティングなどの数値フィールドを更新するために使用され、現在の値を取得したり、新しい値を計算したり、フィールドを更新したりする必要はありません。

パラメータ

  • field: 増分するフィールドの名前。

  • amount: フィールドをインクリメントする量。これは正の値でも負の値でもかまいません。

例 (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()