$slice - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$slice

u $slice pdate 运算符通过限制数组的大小来修改数组。与$push运算符一起使用时,它会限制数组中元素的数量,只保留指定数量的最新或最旧的元素。

参数

  • field:要修改的数组字段。

  • count:要保留的最大元素数。正值保留前 N 个元素,负值保留最后 N 个元素。

示例(MongoDB 外壳)

以下示例演示如何使用$slice更新运算符$push来维护固定大小的近期分数组。

创建示例文档

db.students.insertOne({ _id: 1, name: "Alice", scores: [85, 90, 78] });

查询示例

db.students.updateOne( { _id: 1 }, { $push: { scores: { $each: [92, 88], $slice: -3 } } } )

输出

{ "_id" : 1, "name" : "Alice", "scores" : [ 78, 92, 88 ] }

在此示例中,$slice: -3修饰符在将新值推送到数组后仅保留最后三个元素。

代码示例

要查看使用$slice更新运算符的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function updateDocument() { 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('students'); await collection.updateOne( { _id: 1 }, { $push: { scores: { $each: [92, 88], $slice: -3 } } } ); const updatedDocument = await collection.findOne({ _id: 1 }); console.log(updatedDocument); await client.close(); } updateDocument();
Python
from pymongo import MongoClient def update_document(): 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.students collection.update_one( {'_id': 1}, { '$push': { 'scores': { '$each': [92, 88], '$slice': -3 } } } ) updated_document = collection.find_one({'_id': 1}) print(updated_document) client.close() update_document()