View a markdown version of this page

$firstN - Amazon DocumentDB

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

$firstN

8.0.1 版中的新增内容。

亚马逊 DocumentDB 中的$firstN运算符返回前 N 个元素。当在$group阶段中用作累加器时,它返回每组中前 N 个值的数组。当用作数组表达式运算符时,它返回数组的前 N 个元素。

参数

  • input:解析为要从中返回值的字段或数组的表达式。

  • n:一个正整数,用于指定要返回多少个值。在$group阶段中用作累加器时,n也可以是表达式,只要它根据组_id字段解析为正整数即可。

示例(MongoDB Shell)

以下示例说明如何在聚合期间使用$firstN累加器检索每个项目的前两个数量。

注意

$firstN按照文档到达$group阶段的顺序选择值。要返回特定排序(例如,按日期或分数)的前 N 个值,请在前面添加一个$sort阶段$group

创建示例文档

db.sales.insertMany([ { item: "abc", quantity: 10, date: ISODate("2023-01-01") }, { item: "abc", quantity: 5, date: ISODate("2023-01-02") }, { item: "abc", quantity: 8, date: ISODate("2023-01-03") }, { item: "xyz", quantity: 15, date: ISODate("2023-01-01") }, { item: "xyz", quantity: 7, date: ISODate("2023-01-02") }, { item: "xyz", quantity: 3, date: ISODate("2023-01-03") } ]);

查询示例

db.sales.aggregate([ { $group: { _id: "$item", firstTwoQuantities: { $firstN: { input: "$quantity", n: 2 } } } } ]);

输出

[ { "_id": "abc", "firstTwoQuantities": [10, 5] }, { "_id": "xyz", "firstTwoQuantities": [15, 7] } ]

表达式用法示例(MongoDB Shell)

$firstN运算符也可以用作$project阶段内的表达式,以返回数组字段的前 N 个元素。

创建示例文档

db.inventory.insertMany([ { _id: 1, item: "abc", tags: ["red", "green", "blue", "yellow", "purple"] }, { _id: 2, item: "xyz", tags: ["alpha", "beta", "gamma"] } ]);

查询示例

db.inventory.aggregate([ { $project: { firstThreeTags: { $firstN: { input: "$tags", n: 3 } } }} ]);

输出

[ { "_id": 1, "firstThreeTags": ["red", "green", "blue"] }, { "_id": 2, "firstThreeTags": ["alpha", "beta", "gamma"] } ]

代码示例

要查看使用$firstN累加器的代码示例,请选择要使用的语言的选项卡。以下示例显示了累加器的用法(输入$group)和表达式用法(中$project):

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); try { await client.connect(); const db = client.db('test'); // Accumulator usage: first N values per group const sales = db.collection('sales'); const accumulatorResult = await sales.aggregate([ { $group: { _id: "$item", firstTwoQuantities: { $firstN: { input: "$quantity", n: 2 } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Expression usage: first N elements of an array field const inventory = db.collection('inventory'); const expressionResult = await inventory.aggregate([ { $project: { firstThreeTags: { $firstN: { input: "$tags", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); } finally { 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') try: db = client['test'] # Accumulator usage: first N values per group sales = db['sales'] accumulator_result = list(sales.aggregate([ { '$group': { '_id': '$item', 'firstTwoQuantities': { '$firstN': { 'input': '$quantity', 'n': 2 } } } } ])) print('Accumulator result:', accumulator_result) # Expression usage: first N elements of an array field inventory = db['inventory'] expression_result = list(inventory.aggregate([ { '$project': { 'firstThreeTags': { '$firstN': { 'input': '$tags', 'n': 3 } } } } ])) print('Expression result:', expression_result) finally: client.close() example()