

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

# 更新演算子
<a name="mongo-apis-update-operators"></a>

このセクションでは、Amazon DocumentDB でサポートされている更新演算子に関する詳細情報を提供します。

**Topics**
+ [\$1](dollar-update.md)
+ [\$1[]](dollarBrackets-update.md)
+ [\$1[<identifier>]](dollarIdentifier-update.md)
+ [\$1addToSet](addToSet.md)
+ [\$1bit](bit.md)
+ [\$1currentDate](currentDate.md)
+ [\$1each](each.md)
+ [\$1inc](inc.md)
+ [\$1max](max-update.md)
+ [\$1min](min-update.md)
+ [\$1mul](mul.md)
+ [\$1pop](pop.md)
+ [\$1position](position.md)
+ [\$1pull](pull.md)
+ [\$1pullAll](pullAll.md)
+ [\$1push](push.md)
+ [\$1rename](rename.md)
+ [\$1set](set-update.md)
+ [\$1setOnInsert](setOnInsert.md)
+ [\$1slice](slice-update.md)
+ [\$1sort](sort-update.md)
+ [\$1unset](unset-update.md)

# \$1
<a name="dollar-update"></a>

`$` 位置演算子は、クエリ条件に一致する最初の配列要素を更新します。一致した配列要素の位置のプレースホルダーとして機能します。

**パラメータ**
+ `field.$`: 位置演算子を含む配列フィールド。最初の一致する要素を更新します。

## 例 (MongoDB シェル)
<a name="dollar-update-examples"></a>

次の例は、`$`位置演算子を使用して特定の配列要素を更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.inventory.insertMany([
  { _id: 1, item: "Widget", quantities: [10, 20, 30] },
  { _id: 2, item: "Gadget", quantities: [5, 15, 25] }
]);
```

**クエリの例**

```
db.inventory.updateOne(
  { _id: 1, quantities: 20 },
  { $set: { "quantities.$": 22 } }
);
```

**出力**

```
{
  "_id" : 1,
  "item" : "Widget",
  "quantities" : [ 10, 22, 30 ]
}
```

## コードの例
<a name="dollar-update-code"></a>

`$` 位置演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  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('inventory');

  await collection.updateOne(
    { _id: 1, quantities: 20 },
    { $set: { "quantities.$": 22 } }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    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.inventory

    collection.update_one(
        {'_id': 1, 'quantities': 20},
        {'$set': {'quantities.$': 22}}
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1[]
<a name="dollarBrackets-update"></a>

`$[]` すべての位置演算子は、配列内のすべての要素を更新します。これは、配列フィールドのすべての要素を変更する必要がある場合に使用されます。

**パラメータ**
+ `field.$[]`: すべての要素を更新するすべての位置演算子を含む配列フィールド。

## 例 (MongoDB シェル)
<a name="dollarBrackets-update-examples"></a>

次の例は、 `$[]`演算子を使用してすべての配列要素を更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.products.insertOne({
  _id: 1,
  name: "Laptop",
  prices: [1000, 1100, 1200]
});
```

**クエリの例**

```
db.products.updateOne(
  { _id: 1 },
  { $inc: { "prices.$[]": 50 } }
);
```

**出力**

```
{
  "_id" : 1,
  "name" : "Laptop",
  "prices" : [ 1050, 1150, 1250 ]
}
```

## コードの例
<a name="dollarBrackets-update-code"></a>

`$[]` 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  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('products');

  await collection.updateOne(
    { _id: 1 },
    { $inc: { "prices.$[]": 50 } }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    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.products

    collection.update_one(
        {'_id': 1},
        {'$inc': {'prices.$[]': 50}}
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1[<identifier>]
<a name="dollarIdentifier-update"></a>

`$[<identifier>]` フィルタリングされた位置演算子は、指定されたフィルター条件に一致するすべての配列要素を更新します。これは、配列要素を選択的に更新する `arrayFilters`オプションとともに使用されます。

**パラメータ**
+ `field.$[identifier]`: フィルタリングされた位置演算子を持つ配列フィールド。
+ `arrayFilters`: 更新する要素を決定するフィルター条件の配列。

## 例 (MongoDB シェル)
<a name="dollarIdentifier-update-examples"></a>

次の例は、 `$[<identifier>]`演算子を使用して、条件に基づいて特定の配列要素を更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  grades: [
    { subject: "Math", score: 85 },
    { subject: "Science", score: 92 },
    { subject: "History", score: 78 }
  ]
});
```

**クエリの例**

```
db.students.updateOne(
  { _id: 1 },
  { $inc: { "grades.$[elem].score": 5 } },
  { arrayFilters: [{ "elem.score": { $gte: 80 } }] }
);
```

**出力**

```
{
  "_id" : 1,
  "name" : "Alice",
  "grades" : [
    { "subject" : "Math", "score" : 90 },
    { "subject" : "Science", "score" : 97 },
    { "subject" : "History", "score" : 78 }
  ]
}
```

## コードの例
<a name="dollarIdentifier-update-code"></a>

`$[<identifier>]` 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  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('students');

  await collection.updateOne(
    { _id: 1 },
    { $inc: { "grades.$[elem].score": 5 } },
    { arrayFilters: [{ "elem.score": { $gte: 80 } }] }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    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.students

    collection.update_one(
        {'_id': 1},
        {'$inc': {'grades.$[elem].score': 5}},
        array_filters=[{'elem.score': {'$gte': 80}}]
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1addToSet
<a name="addToSet"></a>

Amazon DocumentDB の `$addToSet`演算子は、値が配列にまだ存在しない場合にのみ、配列に値を追加するために使用されます。これは、配列に一意の要素が含まれていることを確認するのに役立ちます。

**パラメータ**
+ `field`: 更新するフィールド。
+ `value`: 配列フィールドに追加する値。これは単一の値でも式でもかまいません。

## 例 (MongoDB シェル)
<a name="addToSet-examples"></a>

次の例は、 `$addToSet`演算子を使用して配列に一意の要素を追加する方法を示しています。

**サンプルドキュメントを作成する**

```
db.products.insertMany([
  { "_id": 1, "item": "apple", "tags": ["fruit", "red", "round"] },
  { "_id": 2, "item": "banana", "tags": ["fruit", "yellow"] },
  { "_id": 3, "item": "cherry", "tags": ["fruit", "red"] }
])
```

**クエリの例**

```
db.products.update(
  { "item": "apple" },
  { $addToSet: { "tags": "green" } }
)
```

**出力**

```
{ "_id": 1, "item": "apple", "tags": ["fruit", "red", "round", "green"] }
```

この例では、`$addToSet`演算子は「item」フィールドが「apple」であるドキュメントの「tags」配列に「green」タグを追加します。「green」は配列にまだ存在していなかったため、追加されました。

## コードの例
<a name="addToSet-code"></a>

`$addToSet` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ 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('products');

  await collection.updateOne(
    { "item": "apple" },
    { $addToSet: { "tags": "green" } }
  );

  const updatedDoc = await collection.findOne({ "item": "apple" });
  console.log(updatedDoc);

  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.products

    collection.update_one(
        {"item": "apple"},
        {"$addToSet": {"tags": "green"}}
    )

    updated_doc = collection.find_one({"item": "apple"})
    print(updated_doc)

    client.close()

example()
```

------

# \$1bit
<a name="bit"></a>

Amazon DocumentDB の `$bit`演算子を使用すると、特定のフィールドのビットに対してビット単位のオペレーションを実行できます。これは、数値内の個々のビットの状態の設定、クリア、チェックなどのタスクに役立ちます。

**パラメータ**
+ `field`: ビット単位のオペレーションを実行するフィールド。
+ `and`: フィールドでビット単位の AND オペレーションを実行するために使用される整数値。
+ `or`: フィールドでビット単位の OR オペレーションを実行するために使用される整数値。
+ `xor`: フィールドでビット単位の XOR オペレーションを実行するために使用される整数値。

## 例 (MongoDB シェル)
<a name="bit-examples"></a>

次の例は、 `$bit`演算子を使用して数値フィールドに対してビット単位のオペレーションを実行する方法を示しています。

**サンプルドキュメントを作成する**

```
db.numbers.insert([
  { "_id": 1, "number": 5 },
  { "_id": 2, "number": 12 }
])
```

**クエリの例**

```
db.numbers.update(
  { "_id": 1 },
  { "$bit": { "number": { "and": 3 } } }
)
```

**出力**

```
{
  "_id": 1,
  "number": 1
}
```

この例では、 `$bit`演算子を使用して、 が 1 のドキュメントの「数値」フィールドに対してビット単位`_id`の AND オペレーションを実行します。その結果、「数値」フィールドの値は 1 に設定されます。これは、元の値 5 と値 3 の間のビット単位の AND 演算の結果です。

## コードの例
<a name="bit-code"></a>

`$bit` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  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('numbers');

  await collection.updateOne(
    { "_id": 1 },
    { "$bit": { "number": { "and": 3 } } }
  );

  const result = await collection.findOne({ "_id": 1 });
  console.log(result);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

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['numbers']

collection.update_one(
    {"_id": 1},
    {"$bit": {"number": {"and": 3}}}
)

result = collection.find_one({"_id": 1})
print(result)

client.close()
```

------

# \$1currentDate
<a name="currentDate"></a>

`$currentDate` 演算子は、フィールドの値を現在の日付と時刻に設定するために使用されます。この演算子は、ドキュメントが挿入または更新されたときに、現在のタイムスタンプでフィールドを自動的に更新するのに役立ちます。

**パラメータ**
+ `field`: 現在の日付と時刻で更新するフィールド。
+ `type`: (オプション) 現在の日付に使用する BSON タイプを指定します。`date` または `timestamp` のいずれかになります。

## 例 (MongoDB シェル)
<a name="currentDate-examples"></a>

次の例は、 `$currentDate`演算子を使用して、 `lastModified`フィールドを新しいドキュメントが挿入された現在の日時に設定する方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insert({
  name: "John Doe",
  email: "john.doe@example.com"
})
```

**クエリの例**

```
db.users.updateOne(
  { name: "John Doe" },
  { $currentDate: { lastModified: true } }
)
```

**更新されたドキュメントを表示する**

```
db.users.findOne({ name: "John Doe" })
```

**出力**

```
{
  _id: ObjectId('...'),
  name: 'John Doe',
  email: 'john.doe@example.com',
  lastModified: ISODate('2025-10-25T22:50:29.963Z')
}
```

## コードの例
<a name="currentDate-code"></a>

`$currentDate` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateUserWithCurrentDate() {
  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 users = db.collection('users');

  await users.updateOne(
    { name: 'John Doe' },
    { $currentDate: { lastModified: true } }
  );

  console.log('User updated with current date');
  client.close();
}

updateUserWithCurrentDate();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_user_with_current_date():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db.users

    result = users.update_one(
        {'name': 'John Doe'},
        {'$currentDate': {'lastModified': True}}
    )

    print('User updated with current date')
    client.close()

update_user_with_current_date()
```

------

# \$1each
<a name="each"></a>

`$each` 演算子は、 `$push`や などの他の更新演算子と組み合わせて使用され`$addToSet`、配列フィールドに複数の値を追加します。これにより、複数の更新オペレーションを実行するのではなく、1 回のオペレーションで配列に複数の要素を追加できます。

**パラメータ**
+ `value`: 配列フィールドに追加する値の配列。

## 例 (MongoDB シェル)
<a name="each-examples"></a>

次の例は、 `$each`演算子と `$push`演算子を使用して、配列フィールドに複数の要素を追加する方法を示しています。

**サンプルドキュメントを作成する**

```
db.fruits.insertOne({
  _id: 1,
  fruits: ["apple", "banana"]
})
```

**クエリの例**

```
db.fruits.updateOne(
  { _id: 1 },
  { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } }
)
```

**更新されたドキュメントを表示する**

```
db.fruits.findOne({ _id: 1 })
```

**出力**

```
{
  _id: 1,
  fruits: [ 'apple', 'banana', 'cherry', 'durian', 'elderberry' ]
}
```

## コードの例
<a name="each-code"></a>

`$each` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ 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('fruits');

  await collection.updateOne(
    { _id: 1 },
    { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } }
  );

  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['fruits']

    collection.update_one(
        {'_id': 1},
        {'$push': {'fruits': {'$each': ['cherry', 'durian', 'elderberry']}}}
    )

    client.close()

example()
```

------

# \$1inc
<a name="inc"></a>

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

**パラメータ**
+ `field`: 増分するフィールドの名前。
+ `amount`: フィールドをインクリメントする量。これは正の値でも負の値でもかまいません。

## 例 (MongoDB シェル)
<a name="inc-examples"></a>

次の例は、 `$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 }
```

## コードの例
<a name="inc-code"></a>

`$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()
```

------

# \$1max
<a name="max-update"></a>

`$max` 更新演算子は、指定された値が現在のフィールド値より大きい場合にのみ、フィールドの値を更新します。この演算子は、更新全体で最大値を維持するのに役立ちます。

**パラメータ**
+ `field`: 更新するフィールド。
+ `value`: 現在のフィールド値と比較する値。

## 例 (MongoDB シェル)
<a name="max-update-examples"></a>

次の例は、 `$max`演算子を使用してプレイヤーの記録された最高スコアを更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.scores.insertMany([
  { _id: 1, player: "Alice", highScore: 85 },
  { _id: 2, player: "Bob", highScore: 92 },
  { _id: 3, player: "Charlie", highScore: 78 }
])
```

**更新の例**

```
db.scores.updateOne(
  { _id: 1 },
  { $max: { highScore: 95 } }
)
```

**結果**

Alice の `highScore`フィールドは、95 が現在の値である 85 より大きいため、95 に更新されます。

```
{ "_id": 1, "player": "Alice", "highScore": 95 }
```

## コードの例
<a name="max-update-code"></a>

`$max` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ 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('scores');

  const result = await collection.updateOne(
    { _id: 1 },
    { $max: { highScore: 95 } }
  );

  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['scores']

    result = collection.update_one(
        { '_id': 1 },
        { '$max': { 'highScore': 95 } }
    )

    print(result)
    client.close()

example()
```

------

# \$1min
<a name="min-update"></a>

`$min` 更新演算子は、指定された値が現在のフィールド値より小さい場合にのみ、フィールドの値を更新します。この演算子は、更新全体で最小値を維持するのに役立ちます。

**パラメータ**
+ `field`: 更新するフィールド。
+ `value`: 現在のフィールド値と比較する値。

## 例 (MongoDB シェル)
<a name="min-update-examples"></a>

次の例は、 `$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 が現在の値である 15 より小さいため、12 に更新されます。

```
{ "_id": 1, "station": "Station A", "lowestTemp": 12 }
```

## コードの例
<a name="min-update-code"></a>

`$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()
```

------

# \$1mul
<a name="mul"></a>

Amazon DocumentDB の `$mul`演算子は、フィールドの値を指定された数で乗算するために使用されます。これは、クレジットカードのステータスに基づいてフライトマイルを更新するなど、複数のドキュメントをアトミックかつ一貫して更新する場合に便利です。

**パラメータ**
+ `field`: 乗算するフィールド。
+ `multiplier`: フィールド値に乗算する数値。

## 例 (MongoDB シェル)
<a name="mul-examples"></a>

この例では、 `$mul`演算子を使用して、 `credit_card`フィールドが であるすべてのドキュメントの`flight_miles`値を 2 倍にする方法を示します`true`。

**サンプルドキュメントを作成する**

```
db.miles.insertMany([
  { "_id": 1, "member_since": new Date("1987-01-01"), "credit_card": false, "flight_miles": [1205, 2560, 880] },
  { "_id": 2, "member_since": new Date("1982-01-01"), "credit_card": true, "flight_miles": [2410, 5120, 1780, 5560] },
  { "_id": 3, "member_since": new Date("1999-01-01"), "credit_card": true, "flight_miles": [2410, 1760] }
]);
```

**クエリの例**

```
db.miles.update(
  { "credit_card": { "$eq": true } },
  { "$mul": { "flight_miles.$[]": NumberInt(2) } },
  { "multi": true }
);
```

**出力**

```
{ "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ] }
{ "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 4820, 10240, 3560, 11120 ] }
{ "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 4820, 3520 ] }
```

クレジットカードをお持ちのお客様には、フライトマイルが 2 倍になりました。

`$[]` 位置配列演算子は、`flight_miles`配列内の各要素に`$mul`オペレーションを適用するために使用されます。

## コードの例
<a name="mul-code"></a>

`$mul` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateFlightMiles() {
  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('miles');

  await collection.updateMany(
    { credit_card: true },
    { $mul: { 'flight_miles.$[]': 2 } }
  );

  const documents = await collection.find().toArray();
  console.log(documents);

  await client.close();
}

updateFlightMiles();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_flight_miles():
    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.miles

    collection.update_many(
        {'credit_card': True},
        {'$mul': {'flight_miles.$[]': 2}}
    )

    documents = list(collection.find())
    print(documents)

    client.close()

update_flight_miles()
```

------

# \$1pop
<a name="pop"></a>

Amazon DocumentDB の `$pop`演算子は、配列フィールドから最初または最後の要素を削除するために使用されます。これは、固定サイズの配列を維持したり、ドキュメント内にキューのようなデータ構造を実装する必要がある場合に特に便利です。

**パラメータ**
+ `field`: 要素を削除する配列フィールドの名前。
+ `value`: 削除する要素の位置を決定する整数値。の値は最後の要素`1`を削除し、 の値は最初の要素`-1`を削除します。

## 例 (MongoDB シェル)
<a name="pop-examples"></a>

この例では、 `$pop`演算子を使用して配列フィールドから最初と最後の要素を削除する方法を示します。

**サンプルドキュメントを作成する**

```
db.users.insertMany([
  { "_id": 1, "name": "John Doe", "hobbies": ["reading", "swimming", "hiking"] },
  { "_id": 2, "name": "Jane Smith", "hobbies": ["cooking", "gardening", "painting"] }
])
```

**クエリの例**

```
// Remove the first element from the "hobbies" array
db.users.update({ "_id": 1 }, { $pop: { "hobbies": -1 } })

// Remove the last element from the "hobbies" array
db.users.update({ "_id": 2 }, { $pop: { "hobbies": 1 } })
```

**出力**

```
{ "_id" : 1, "name" : "John Doe", "hobbies" : [ "swimming", "hiking" ] }
{ "_id" : 2, "name" : "Jane Smith", "hobbies" : [ "cooking", "gardening" ] }
```

## コードの例
<a name="pop-code"></a>

`$pop` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ 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('users');

  // Remove the first element from the "hobbies" array
  await collection.updateOne({ "_id": 1 }, { $pop: { "hobbies": -1 } });

  // Remove the last element from the "hobbies" array
  await collection.updateOne({ "_id": 2 }, { $pop: { "hobbies": 1 } });

  const users = await collection.find().toArray();
  console.log(users);

  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['users']

    # Remove the first element from the "hobbies" array
    collection.update_one({"_id": 1}, {"$pop": {"hobbies": -1}})

    # Remove the last element from the "hobbies" array
    collection.update_one({"_id": 2}, {"$pop": {"hobbies": 1}})

    users = list(collection.find())
    print(users)

    client.close()

example()
```

------

# \$1position
<a name="position"></a>

Amazon DocumentDB `$position` の修飾子は、`$push`演算子が要素を挿入する配列内の場所を指定します。`$position` 修飾子がない場合、`$push`演算子は配列の末尾に要素を挿入します。

**パラメータ**
+ `field`: 更新する配列フィールド。
+ `num`: ゼロベースのインデックス作成に基づいて要素を挿入する配列内の位置。

**注**: `$position`修飾子を使用するには、`$each`修飾子とともに表示する必要があります。

## 例 (MongoDB シェル)
<a name="position-examples"></a>

次の例は、 `$position`演算子を使用してプロジェクト管理システム内の特定の位置にタスクを挿入する方法を示しています。

**サンプルドキュメントを作成する**

```
db.projects.insertOne({ "_id": 1, "name": "Website Redesign", "tasks": ["Design mockups"] })
```

**クエリ例 1 - 緊急タスクを最初に追加する**

```
db.projects.updateOne(
   { _id: 1 },
   {
     $push: {
        tasks: {
           $each: ["Security audit", "Performance review"],
           $position: 0
        }
     }
   }
)
```

**出力 1**

```
{ "_id": 1, "name": "Website Redesign", "tasks": ["Security audit", "Performance review", "Design mockups"] }
```

**クエリの例 2 - 特定の位置にタスクを追加する**

```
db.projects.insertOne({ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Deploy to store"] })

db.projects.updateOne(
   { _id: 2 },
   {
     $push: {
        tasks: {
           $each: ["Code review", "Testing phase"],
           $position: 2
        }
     }
   }
)
```

**出力 2**

```
{ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Code review", "Testing phase", "Deploy to store"] }
```

## コードの例
<a name="position-code"></a>

`$position` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function insertTasksAtPosition() {
  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('projects');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        tasks: {
          $each: ["Security audit", "Performance review"],
          $position: 0
        }
      }
    }
  );

  const updatedProject = await collection.findOne({ _id: 1 });
  console.log(updatedProject);

  await client.close();
}

insertTasksAtPosition();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def insert_tasks_at_position():
    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['projects']

    result = collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'tasks': {
                    '$each': ['Security audit', 'Performance review'],
                    '$position': 0
                }
            }
        }
    )

    updated_project = collection.find_one({'_id': 1})
    print(updated_project)

    client.close()

insert_tasks_at_position()
```

------

# \$1pull
<a name="pull"></a>

`$pull` 演算子は、指定された条件に一致する値または値のすべてのインスタンスを配列から削除するために使用されます。この演算子は、ドキュメント内の配列フィールドから特定の要素を削除する必要がある場合に便利です。

**パラメータ**
+ `field`: 値を削除する配列フィールドの名前 (複数可）。
+ `value`: 配列から削除する要素 (複数可) を決定する値または条件。

## 例 (MongoDB シェル)
<a name="pull-examples"></a>

次の例は、 `$pull`演算子を使用して配列フィールドから要素を削除する方法を示しています。

**サンプルドキュメントを作成する**

```
db.restaurants.insertMany([
  {
    name: "Pizza Hut",
    cuisine: "Italian",
    features: ["Delivery", "Takeout", "Dine-in"]
  },
  {
    name: "Sushi Saito",
    cuisine: "Japanese",
    features: ["Dine-in", "Private Dining"]
  },
  {
    name: "Taco Bell",
    cuisine: "Mexican",
    features: ["Delivery", "Takeout", "Drive-thru"]
  }
])
```

**クエリの例**

```
db.restaurants.updateMany(
  { cuisine: "Italian" },
  { $pull: { features: "Takeout" } }
)
```

**出力**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

上記のクエリは、 `cuisine`フィールドが「イタリア語」であるすべてのドキュメントから「テイクアウト」機能を削除します。

## コードの例
<a name="pull-code"></a>

`$pull` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateRestaurants() {
  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 restaurants = db.collection('restaurants');

  await restaurants.updateMany(
    { cuisine: 'Italian' },
    { $pull: { features: 'Takeout' } }
  );

  const updatedRestaurants = await restaurants.find({}).toArray();
  console.log(updatedRestaurants);

  await client.close();
}

updateRestaurants();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_restaurants():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    restaurants = db.restaurants

    result = restaurants.update_many(
        { 'cuisine': 'Italian' },
        { '$pull': { 'features': 'Takeout' } }
    )

    updated_restaurants = list(restaurants.find({}))
    print(updated_restaurants)

    client.close()

update_restaurants()
```

------

# \$1pullAll
<a name="pullAll"></a>

Amazon DocumentDB の `$pullAll`演算子は、指定された値のすべてのインスタンスを配列フィールドから削除するために使用されます。これは、1 回のオペレーションで配列から複数の要素を削除する必要がある場合に特に便利です。

**パラメータ**
+ `field`: 要素を削除する配列フィールドの名前。
+ `value`: 配列フィールドから削除する値の配列。

## 例 (MongoDB シェル)
<a name="pullAll-examples"></a>

次の例は、 `$pullAll`演算子を使用して配列フィールドから複数の要素を削除する方法を示しています。

**サンプルドキュメントを作成する**

```
db.restaurants.insert([
  {
    "name": "Taj Mahal",
    "cuisine": "Indian",
    "features": ["Private Dining", "Live Music"]
  },
  {
    "name": "Golden Palace",
    "cuisine": "Chinese",
    "features": ["Private Dining", "Takeout"]
  },
  {
    "name": "Olive Garden",
    "cuisine": "Italian",
    "features": ["Private Dining", "Outdoor Seating"]
  }
])
```

**クエリの例**

```
db.restaurants.update(
  { "name": "Taj Mahal" },
  { $pullAll: { "features": ["Private Dining", "Live Music"] } }
)
```

**出力**

```
{
  "name": "Taj Mahal",
  "cuisine": "Indian",
  "features": []
}
```

## コードの例
<a name="pullAll-code"></a>

`$pullAll` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function main() {
  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('restaurants');

  await collection.updateMany(
    { "name": "Taj Mahal" },
    { $pullAll: { "features": ["Private Dining", "Live Music"] } }
  );

  const updatedDocument = await collection.findOne({ "name": "Taj Mahal" });
  console.log(updatedDocument);

  await client.close();
}

main();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def main():
    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['restaurants']

    collection.update_many(
        {"name": "Taj Mahal"},
        {"$pullAll": {"features": ["Private Dining", "Live Music"]}}
    )

    updated_document = collection.find_one({"name": "Taj Mahal"})
    print(updated_document)

    client.close()

if __name__ == '__main__':
    main()
```

------

# \$1push
<a name="push"></a>

Amazon DocumentDB の `$push`演算子は、ドキュメントの配列フィールドに項目を追加するために使用されます。この演算子は、配列全体を上書きせずに既存の配列に新しいデータを追加する必要がある場合に特に便利です。

**パラメータ**
+ `field`: 新しい要素を追加する配列フィールドの名前。
+ `value`: 配列に追加する値。
+ `position`: (オプション) 新しい要素を追加する配列内の位置を指定する修飾子。サポートされている修飾子には、 `$` (配列の末尾に を追加) と `$[]` (配列の末尾に を追加し、配列フィルターを無視) が含まれます。

## 例 (MongoDB シェル)
<a name="push-examples"></a>

次の例は、 `$push`演算子を使用してドキュメントの配列フィールドに新しい要素を追加する方法を示しています。

**サンプルドキュメントを作成する**

```
db.users.insert([
  { _id: 1, name: "John Doe", hobbies: ["reading", "swimming"] },
  { _id: 2, name: "Jane Smith", hobbies: ["gardening", "cooking"] }
])
```

**クエリの例**

```
db.users.updateOne(
  { _id: 1 },
  { $push: { hobbies: "hiking" } }
)
```

**出力**

```
{
  "acknowledged" : true,
  "matchedCount" : 1,
  "modifiedCount" : 1
}
```

更新を実行すると、 を持つドキュメントの`hobbies`配列`_id: 1`が に更新されます`[&quot;reading&quot;, &quot;swimming&quot;, &quot;hiking&quot;]`。

## コードの例
<a name="push-code"></a>

`$push` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  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: 1 },
    { $push: { hobbies: "hiking" } }
  );

  console.log(result);
  client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    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': 1},
        {'$push': {'hobbies': 'hiking'}}
    )

    print(result.raw_result)
    client.close()

update_document()
```

------

# \$1rename
<a name="rename"></a>

Amazon DocumentDB の `$rename`演算子は、ドキュメント内のフィールドの名前を変更するために使用されます。この演算子は、ドキュメントの構造を更新したり、新しいデータモデルに合わせる必要がある場合に特に役立ちます。

**パラメータ**
+ `field`: 名前を変更するフィールド。
+ `newName`: フィールドの新しい名前。

## 例 (MongoDB シェル)
<a name="rename-examples"></a>

次の例は、 `$rename`演算子を使用して、 `&quot;Date.DoW&quot;` フィールドを に設定してドキュメント`&quot;Date.DayOfWeek&quot;`内の `&quot;DocName&quot;`フィールドの名前を に変更する方法を示しています`&quot;Document 1&quot;`。

**サンプルドキュメントを作成する**

```
db.example.insertOne({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**クエリの例**

```
db.example.update(
    { "DocName": "Document 1" },
    { $rename: { "Date.DoW": "Date.DayOfWeek" } }
)
```

**出力**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DayOfWeek": "Saturday"
    },
    "Words": 2482
}
```

## コードの例
<a name="rename-code"></a>

`$rename` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ 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('example');

    await collection.updateOne(
        { "DocName": "Document 1" },
        { $rename: { "Date.DoW": "Date.DayOfWeek" } }
    );

    const updatedDoc = await collection.findOne({ "DocName": "Document 1" });
    console.log(updatedDoc);

    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['example']

    collection.update_one(
        {"DocName": "Document 1"},
        {"$rename": {"Date.DoW": "Date.DayOfWeek"}}
    )

    updated_doc = collection.find_one({"DocName": "Document 1"})
    print(updated_doc)

    client.close()

example()
```

------

# \$1set
<a name="set-update"></a>

Amazon DocumentDB の `$set`演算子は、ドキュメント内の指定されたフィールドの値を更新するために使用されます。この演算子を使用すると、新しいフィールドを追加したり、ドキュメント内の既存のフィールドを変更したりできます。これは、Amazon DocumentDB と互換性のある MongoDB Java ドライバーの基本的な更新演算子です。

**パラメータ**
+ `field`: 更新するフィールド。
+ `value`: フィールドの新しい値。

## 例 (MongoDB シェル)
<a name="set-examples"></a>

次の例は、 `$set`演算子を使用してドキュメントの `Item`フィールドを更新する方法を示しています。

**サンプルドキュメントを作成する**

```
db.example.insert([
  {
    "Item": "Pen",
    "Colors": ["Red", "Green", "Blue", "Black"],
    "Inventory": {
      "OnHand": 244,
      "MinOnHand": 72
    }
  },
  {
    "Item": "Poster Paint",
    "Colors": ["Red", "Green", "Blue", "White"],
    "Inventory": {
      "OnHand": 120,
      "MinOnHand": 36
    }
  }
])
```

**クエリの例**

```
db.example.update(
  { "Item": "Pen" },
  { $set: { "Item": "Gel Pen" } }
)
```

**出力**

```
{
  "Item": "Gel Pen",
  "Colors": ["Red", "Green", "Blue", "Black"],
  "Inventory": {
    "OnHand": 244,
    "MinOnHand": 72
  }
}
```

## コードの例
<a name="set-code"></a>

`$set` コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  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('example');

  await collection.updateOne(
    { "Item": "Pen" },
    { $set: { "Item": "Gel Pen" } }
  );

  const updatedDocument = await collection.findOne({ "Item": "Gel Pen" });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    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.example

    collection.update_one(
        {"Item": "Pen"},
        {"$set": {"Item": "Gel Pen"}}
    )

    updated_document = collection.find_one({"Item": "Gel Pen"})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1setOnInsert
<a name="setOnInsert"></a>

Amazon DocumentDB の `$setOnInsert`演算子は、ドキュメントが挿入されている場合はフィールドの値を設定するために使用されますが、ドキュメントが更新されている場合は効果がありません。

**パラメータ**
+ `field`: 設定するフィールド。
+ `value`: フィールドに割り当てる値。

## 例 (MongoDB シェル)
<a name="setOnInsert-examples"></a>

次の例は、Amazon DocumentDB での `$setOnInsert`演算子の使用を示しています。ドキュメントがまだ存在しない場合は新しいドキュメントが作成されますが、ドキュメントが更新されている場合は効果がありません。

**サンプルドキュメントを作成する**

```
db.users.insertOne({
  _id: 1,
  name: "John Doe",
  age: 30
})
```

**クエリ例 1 - 既存のドキュメントを更新する**

```
db.users.update(
  { _id: 1 },
  {
    $set: { age: 31 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)
```

**出力 1**

```
{
  _id: 1,
  name: "John Doe",
  age: 31
}
```

出力は、ドキュメントが更新されたが、ドキュメントがすでに存在しているため、 `createdAt` フィールドは**追加されていない**ことを示しています。`$setOnInsert` 演算子は、新しいドキュメントを挿入する場合にのみ適用されます。

**クエリ例 2 - 新しいドキュメントを挿入する (アップサート)**

```
db.users.update(
  { _id: 2 },
  {
    $set: { name: "Jane Smith", age: 25 },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
)
```

**出力 2**

```
{
  _id: 2,
  name: "Jane Smith", 
  age: 25,
  createdAt: ISODate("2025-10-31T09:57:52.459Z")
}
}
```

## コードの例
<a name="setOnInsert-code"></a>

`$setOnInsert` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateWithSetOnInsert() {
  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 users = db.collection('users');

  await users.updateOne(
    { _id: 1 },
    {
      $set: { age: 31 },
      $setOnInsert: { createdAt: new Date() }
    },
    { upsert: true }
  );

  const updatedUser = await users.findOne({ _id: 1 });
  console.log(updatedUser);

  await client.close();
}

updateWithSetOnInsert();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_with_set_on_insert():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    result = users.update_one(
        {'_id': 1},
        {
            '$set': {'age': 31},
            '$setOnInsert': {'createdAt': datetime.datetime.now()}
        },
        upsert=True
    )

    updated_user = users.find_one({'_id': 1})
    print(updated_user)

    client.close()

update_with_set_on_insert()
```

------

# \$1slice
<a name="slice-update"></a>

`$slice` 更新演算子は、配列のサイズを制限して配列を変更します。`$push` 演算子とともに使用すると、配列内の要素の数が制限され、指定された数の最新の要素または最も古い要素のみが保持されます。

**パラメータ**
+ `field`: 変更する配列フィールド。
+ `count`: 保持する要素の最大数。正の値は最初の N 要素を保持し、負の値は最後の N 要素を保持します。

## 例 (MongoDB シェル)
<a name="slice-update-examples"></a>

次の例は、 で`$slice`更新演算子を使用して`$push`、最近のスコアの固定サイズの配列を維持する方法を示しています。

**サンプルドキュメントを作成する**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  scores: [85, 90, 78]
});
```

**クエリの例**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      scores: {
        $each: [92, 88],
        $slice: -3
      }
    }
  }
)
```

**出力**

```
{
  "_id" : 1,
  "name" : "Alice",
  "scores" : [ 78, 92, 88 ]
}
```

この例では、修飾子は、配列に新しい値をプッシュした後、最後の `$slice: -3` 3 つの要素のみを保持します。

## コードの例
<a name="slice-update-code"></a>

`$slice` 更新演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  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('students');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        scores: {
          $each: [92, 88],
          $slice: -3
        }
      }
    }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    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.students

    collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'scores': {
                    '$each': [92, 88],
                    '$slice': -3
                }
            }
        }
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1sort
<a name="sort-update"></a>

`$sort` 更新修飾子は、 `$push`演算子で使用すると配列要素を順序付けします。指定されたフィールド値または要素自体に基づいて、配列要素を昇順または降順に配置します。

**パラメータ**
+ `field`: 変更する配列フィールド。
+ `order`: 昇順`-1`または降順`1`に使用します。

## 例 (MongoDB シェル)
<a name="sort-update-examples"></a>

次の例は、 `$sort` で 修飾子を使用して新しいクイズスコアを追加し`$push`、降順でソートされたままにする方法を示しています。

**サンプルドキュメントを作成する**

```
db.students.insertOne({
  _id: 1,
  name: "Bob",
  quizzes: [
    { score: 85, date: "2024-01-15" },
    { score: 92, date: "2024-02-10" }
  ]
});
```

**クエリの例**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      quizzes: {
        $each: [{ score: 78, date: "2024-03-05" }],
        $sort: { score: -1 }
      }
    }
  }
)
```

**出力**

```
{
  "_id" : 1,
  "name" : "Bob",
  "quizzes" : [
    { "score" : 92, "date" : "2024-02-10" },
    { "score" : 85, "date" : "2024-01-15" },
    { "score" : 78, "date" : "2024-03-05" }
  ]
}
```

## コードの例
<a name="sort-update-code"></a>

`$sort` 更新修飾子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateDocument() {
  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('students');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        quizzes: {
          $each: [{ score: 78, date: "2024-03-05" }],
          $sort: { score: -1 }
        }
      }
    }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_document():
    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.students

    collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'quizzes': {
                    '$each': [{'score': 78, 'date': '2024-03-05'}],
                    '$sort': {'score': -1}
                }
            }
        }
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------

# \$1unset
<a name="unset-update"></a>

Amazon DocumentDB の `$unset`演算子は、ドキュメントから指定されたフィールドを削除するために使用されます。を使用してフィールドを削除すると`$unset`、そのフィールドはドキュメントから削除され、それに応じてドキュメントのサイズが小さくなります。これは、ドキュメントから不要なデータを削除する場合に便利です。

**パラメータ**
+ `field`: ドキュメントから削除するフィールド。これは、単一のフィールドでも、ネストされたフィールドへの点線のパスでもかまいません。

## 例 (MongoDB シェル)
<a name="unset-examples"></a>

次の例は、 `$unset`演算子を使用して`example`コレクション内のドキュメントから `Words`フィールドを削除する方法を示しています。

**サンプルドキュメントを作成する**

```
db.example.insert({
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    },
    "Words": 2482
})
```

**クエリの例**

```
db.example.update(
    { "DocName" : "Document 1" },
    { $unset: { Words:1 } }
)
```

**出力**

```
{
    "DocName": "Document 1",
    "Date": {
        "Month": 4,
        "Day": 18,
        "Year": 1987,
        "DoW": "Saturday"
    }
}
```

この例では、 `$unset`演算子を使用して、「ドキュメント 1」と`DocName`等しい `Words` フィールドをドキュメントから削除します。結果のドキュメントに `Words`フィールドが含まれなくなりました。

## コードの例
<a name="unset-code"></a>

`$unset` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function removeField() {
  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('example');

  const result = await collection.updateOne(
    { "DocName": "Document 1" },
    { $unset: { "Words": 1 } }
  );

  console.log(`Modified ${result.modifiedCount} document(s)`);
  client.close();
}

removeField();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def remove_field():
    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['example']

    result = collection.update_one(
        {"DocName": "Document 1"},
        {"$unset": {"Words": 1}}
    )

    print(f"Modified {result.modified_count} document(s)")
    client.close()

remove_field()
```

------