$slice - Amazon DocumentDB

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

$slice

$slice聚合运算符使您可以通过从数组的开头或结尾遍历数组来返回数组的子集。这用于显示数组字段中有限数量的项目,例如顶部或底部 N 个项目。

参数

  • array: 要切片的数组字段。

  • n:一个整数,它指定要返回的元素数。正值从数组的开头开始,而负值从数组的末尾开始。

示例(MongoDB 外壳)

以下示例演示如何使用$slice返回每位厨师最喜欢的前两个糖果。

创建示例文档

db.sweets.insertMany([ { "_id" : 1, "name" : "Alvin", "favorites": [ "chocolate", "cake", "toffee", "beignets" ] }, { "_id" : 2, "name" : "Tom", "favorites": [ "donuts", "pudding", "pie" ] }, { "_id" : 3, "name" : "Jessica", "favorites": [ "fudge", "smores", "pudding", "cupcakes" ] }, { "_id" : 4, "name" : "Rachel", "favorites": [ "ice cream" ] } ]);

查询示例

db.sweets.aggregate([ { $project: { _id: 0, name: 1, topTwoFavorites: { $slice: [ "$favorites", 2 ] } } } ]);

输出

[ { name: 'Alvin', topTwoFavorites: [ 'chocolate', 'cake' ] }, { name: 'Tom', topTwoFavorites: [ 'donuts', 'pudding' ] }, { name: 'Jessica', topTwoFavorites: [ 'fudge', 'smores' ] }, { name: 'Rachel', topTwoFavorites: [ 'ice cream' ] } ]

在此示例中,$slice运算符用于从每个文档的favorites数组中提取前两个元素。

代码示例

要查看使用该$slice命令的代码示例,请选择要使用的语言的选项卡:

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('sweets'); const result = await collection.aggregate([ { $project: { name: 1, topTwoFavorites: { $slice: ['$favorites', 2] } } } ]).toArray(); console.log(result); 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['sweets'] result = list(collection.aggregate([ { '$project': { 'name': 1, 'topTwoFavorites': { '$slice': ['$favorites', 2] } } } ])) print(result) client.close() example()