$position - Amazon DocumentDB

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

$position

Amazon DocumentDB $position 中的修飾詞會指定$push運算子插入元素的陣列中的位置。$position 如果沒有修改器,$push運算子會將元素插入陣列的結尾。

參數

  • field:要更新的陣列欄位。

  • num:陣列中應插入元素的位置,以零為基礎編製索引。

注意:若要使用$position修飾詞,它必須與$each修飾詞一起顯示。

範例 (MongoDB Shell)

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