$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()