

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

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

------