Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$pullAll
Amazon DocumentDB 中的$pullAll运算符用于从数组字段中删除指定值的所有实例。当你需要在一次操作中从数组中移除多个元素时,这特别有用。
参数
-
field:要从中移除元素的数组字段的名称。
-
value:要从数组字段中移除的值数组。
示例(MongoDB 外壳)
以下示例演示如何使用$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": []
}
代码示例
要查看使用该$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()