Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$addToSet
仅当数组中尚不存在值时,Amazon DocumentDB 中的$addToSet运算符才用于向该数组添加值。这对于确保数组包含唯一元素很有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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操作员将 “绿色” 标签添加到文档的 “标签” 数组中,其中 “项目” 字段为 “apple”。由于 “green” 不在数组中,因此已将其添加。
代码示例
要查看使用该$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()