本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$pop
Amazon DocumentDB 中的$pop运算符用于从数组字段中删除第一个或最后一个元素。当您需要维护固定大小的数组或在文档中实现类似队列的数据结构时,它特别有用。
参数
示例(MongoDB 外壳)
此示例演示如何使用$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()