本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$pop
Amazon DocumentDB 中的$pop運算子用於從陣列欄位移除第一個或最後一個元素。當您需要維護固定大小的陣列或在文件中實作類似佇列的資料結構時,此功能特別有用。
參數
範例 (MongoDB Shell)
此範例示範如何使用 $pop 運算子從陣列欄位移除第一個和最後一個元素。
建立範例文件
db.users.insertMany([
{ "_id": 1, "name": "John Doe", "hobbies": ["reading", "swimming", "hiking"] },
{ "_id": 2, "name": "Jane Smith", "hobbies": ["cooking", "gardening", "painting"] }
])
查詢範例
// Remove the first element from the "hobbies" array
db.users.update({ "_id": 1 }, { $pop: { "hobbies": -1 } })
// Remove the last element from the "hobbies" array
db.users.update({ "_id": 2 }, { $pop: { "hobbies": 1 } })
輸出
{ "_id" : 1, "name" : "John Doe", "hobbies" : [ "swimming", "hiking" ] }
{ "_id" : 2, "name" : "Jane Smith", "hobbies" : [ "cooking", "gardening" ] }
程式碼範例
若要檢視使用 $pop命令的程式碼範例,請選擇您要使用的語言標籤:
- 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('users');
// Remove the first element from the "hobbies" array
await collection.updateOne({ "_id": 1 }, { $pop: { "hobbies": -1 } });
// Remove the last element from the "hobbies" array
await collection.updateOne({ "_id": 2 }, { $pop: { "hobbies": 1 } });
const users = await collection.find().toArray();
console.log(users);
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['users']
# Remove the first element from the "hobbies" array
collection.update_one({"_id": 1}, {"$pop": {"hobbies": -1}})
# Remove the last element from the "hobbies" array
collection.update_one({"_id": 2}, {"$pop": {"hobbies": 1}})
users = list(collection.find())
print(users)
client.close()
example()