$pull - Amazon DocumentDB

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

$pull

$pull运算符用于从数组中删除一个或多个与指定条件匹配的值的所有实例。当您需要从文档中的数组字段中删除特定元素时,此运算符很有用。

参数

  • field:要从中删除值的数组字段的名称。

  • value:决定要从数组中删除哪些元素的值或条件。

示例(MongoDB 外壳)

以下示例演示如何使用$pull运算符从数组字段中移除元素。

创建示例文档

db.restaurants.insertMany([ { name: "Pizza Hut", cuisine: "Italian", features: ["Delivery", "Takeout", "Dine-in"] }, { name: "Sushi Saito", cuisine: "Japanese", features: ["Dine-in", "Private Dining"] }, { name: "Taco Bell", cuisine: "Mexican", features: ["Delivery", "Takeout", "Drive-thru"] } ])

查询示例

db.restaurants.updateMany( { cuisine: "Italian" }, { $pull: { features: "Takeout" } } )

输出

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

上面的查询从所有cuisine字段为 “意大利语” 的文档中删除 “Takeout” 功能。

代码示例

要查看使用该$pull命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function updateRestaurants() { 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 restaurants = db.collection('restaurants'); await restaurants.updateMany( { cuisine: 'Italian' }, { $pull: { features: 'Takeout' } } ); const updatedRestaurants = await restaurants.find({}).toArray(); console.log(updatedRestaurants); await client.close(); } updateRestaurants();
Python
from pymongo import MongoClient def update_restaurants(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client.test restaurants = db.restaurants result = restaurants.update_many( { 'cuisine': 'Italian' }, { '$pull': { 'features': 'Takeout' } } ) updated_restaurants = list(restaurants.find({})) print(updated_restaurants) client.close() update_restaurants()