$pullAll - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$pullAll

Amazon DocumentDB 中的$pullAll運算子用於從陣列欄位移除指定值的所有執行個體。當您需要在單一操作中移除陣列中的多個元素時,此功能特別有用。

參數

  • field:要從中移除元素的陣列欄位名稱。

  • value:要從陣列欄位移除的值陣列。

範例 (MongoDB Shell)

下列範例示範如何使用 $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()