$position - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$position

Amazon DocumentDB $position の修飾子は、$push演算子が要素を挿入する配列内の場所を指定します。$position 修飾子がない場合、$push演算子は配列の末尾に要素を挿入します。

パラメータ

  • field: 更新する配列フィールド。

  • num: ゼロベースのインデックス作成に基づいて要素を挿入する配列内の位置。

: $position修飾子を使用するには、$each修飾子とともに表示する必要があります。

例 (MongoDB シェル)

次の例は、 $position演算子を使用してプロジェクト管理システム内の特定の位置にタスクを挿入する方法を示しています。

サンプルドキュメントを作成する

db.projects.insertOne({ "_id": 1, "name": "Website Redesign", "tasks": ["Design mockups"] })

クエリ例 1 - 緊急タスクを最初に追加する

db.projects.updateOne( { _id: 1 }, { $push: { tasks: { $each: ["Security audit", "Performance review"], $position: 0 } } } )

出力 1

{ "_id": 1, "name": "Website Redesign", "tasks": ["Security audit", "Performance review", "Design mockups"] }

クエリの例 2 - 特定の位置にタスクを追加する

db.projects.insertOne({ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Deploy to store"] }) db.projects.updateOne( { _id: 2 }, { $push: { tasks: { $each: ["Code review", "Testing phase"], $position: 2 } } } )

出力 2

{ "_id": 2, "name": "Mobile App", "tasks": ["Setup project", "Create wireframes", "Code review", "Testing phase", "Deploy to store"] }

コードの例

$position コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

Node.js
const { MongoClient } = require('mongodb'); async function insertTasksAtPosition() { 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('projects'); await collection.updateOne( { _id: 1 }, { $push: { tasks: { $each: ["Security audit", "Performance review"], $position: 0 } } } ); const updatedProject = await collection.findOne({ _id: 1 }); console.log(updatedProject); await client.close(); } insertTasksAtPosition();
Python
from pymongo import MongoClient def insert_tasks_at_position(): 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['projects'] result = collection.update_one( {'_id': 1}, { '$push': { 'tasks': { '$each': ['Security audit', 'Performance review'], '$position': 0 } } } ) updated_project = collection.find_one({'_id': 1}) print(updated_project) client.close() insert_tasks_at_position()