Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$push
Amazon DocumentDB 中的$push运算符用于向文档的数组字段中添加项目。当您需要在不覆盖整个数组的情况下向现有数组追加新数据时,此运算符特别有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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将更新为["reading", "swimming", "hiking"]。
代码示例
要查看使用该$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()