翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$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()