

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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

------