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"] } ]

窗口运算符用法示例(MongoDB Shell)

8.0.2 版中的新内容。

该$firstN操作员还可以在$setWindowFields舞台中用作窗口操作员。在这种情况下,它返回一个包含每个窗口中文档的第一个n值的数组。您可以在output字段下指定运算符,也可以选择使用window文档定义窗口边界。

注意

在中用作窗口运算符时$setWindowFields,中间数据限制$firstN为 100 MB。超过此限制的操作会返回错误。

创建示例文档

db.stockPrices.insertMany([ { _id: 1, ticker: "ABC", hour: 1, price: 50 }, { _id: 2, ticker: "ABC", hour: 2, price: 45 }, { _id: 3, ticker: "ABC", hour: 3, price: 60 }, { _id: 4, ticker: "ABC", hour: 4, price: 40 }, { _id: 5, ticker: "XYZ", hour: 1, price: 30 }, { _id: 6, ticker: "XYZ", hour: 2, price: 35 }, { _id: 7, ticker: "XYZ", hour: 3, price: 25 } ]);

查询示例

以下示例对文档进行分区ticker,按分区排序hour,并返回从分区开始到当前文档的前两个价格。

db.stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { firstTwoSoFar: { $firstN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]);

输出

[ { "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "firstTwoSoFar": [50] }, { "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "firstTwoSoFar": [50, 45] }, { "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "firstTwoSoFar": [50, 45] }, { "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "firstTwoSoFar": [50, 45] }, { "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "firstTwoSoFar": [30] }, { "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "firstTwoSoFar": [30, 35] }, { "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "firstTwoSoFar": [30, 35] } ]

每个文档都使用firstTwoSoFar其窗口中的前两个price值(hour按顺序排列)进行扩展。

代码示例

要查看使用$firstN运算符的代码示例,请选择要使用的语言的选项卡。以下示例显示累加器的用法 (in$group)、表达式的用法 (in$project) 和窗口运算符的用法 (in$setWindowFields):

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'); await sales.insertMany([ { item: "abc", quantity: 10, date: new Date("2023-01-01") }, { item: "abc", quantity: 5, date: new Date("2023-01-02") }, { item: "abc", quantity: 8, date: new Date("2023-01-03") }, { item: "xyz", quantity: 15, date: new Date("2023-01-01") }, { item: "xyz", quantity: 7, date: new Date("2023-01-02") }, { item: "xyz", quantity: 3, date: new Date("2023-01-03") } ]); 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'); await inventory.insertMany([ { _id: 1, item: "abc", tags: ["red", "green", "blue", "yellow", "purple"] }, { _id: 2, item: "xyz", tags: ["alpha", "beta", "gamma"] } ]); const expressionResult = await inventory.aggregate([ { $project: { firstThreeTags: { $firstN: { input: "$tags", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); // Window operator usage: first N values over a window in each partition const stockPrices = db.collection('stockPrices'); await stockPrices.insertMany([ { _id: 1, ticker: "ABC", hour: 1, price: 50 }, { _id: 2, ticker: "ABC", hour: 2, price: 45 }, { _id: 3, ticker: "ABC", hour: 3, price: 60 }, { _id: 4, ticker: "ABC", hour: 4, price: 40 }, { _id: 5, ticker: "XYZ", hour: 1, price: 30 }, { _id: 6, ticker: "XYZ", hour: 2, price: 35 }, { _id: 7, ticker: "XYZ", hour: 3, price: 25 } ]); const windowResult = await stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { firstTwoSoFar: { $firstN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient from datetime import datetime 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'] sales.insert_many([ { 'item': 'abc', 'quantity': 10, 'date': datetime(2023, 1, 1) }, { 'item': 'abc', 'quantity': 5, 'date': datetime(2023, 1, 2) }, { 'item': 'abc', 'quantity': 8, 'date': datetime(2023, 1, 3) }, { 'item': 'xyz', 'quantity': 15, 'date': datetime(2023, 1, 1) }, { 'item': 'xyz', 'quantity': 7, 'date': datetime(2023, 1, 2) }, { 'item': 'xyz', 'quantity': 3, 'date': datetime(2023, 1, 3) } ]) 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'] inventory.insert_many([ { '_id': 1, 'item': 'abc', 'tags': ['red', 'green', 'blue', 'yellow', 'purple'] }, { '_id': 2, 'item': 'xyz', 'tags': ['alpha', 'beta', 'gamma'] } ]) expression_result = list(inventory.aggregate([ { '$project': { 'firstThreeTags': { '$firstN': { 'input': '$tags', 'n': 3 } } } } ])) print('Expression result:', expression_result) # Window operator usage: first N values over a window in each partition stock_prices = db['stockPrices'] stock_prices.insert_many([ { '_id': 1, 'ticker': 'ABC', 'hour': 1, 'price': 50 }, { '_id': 2, 'ticker': 'ABC', 'hour': 2, 'price': 45 }, { '_id': 3, 'ticker': 'ABC', 'hour': 3, 'price': 60 }, { '_id': 4, 'ticker': 'ABC', 'hour': 4, 'price': 40 }, { '_id': 5, 'ticker': 'XYZ', 'hour': 1, 'price': 30 }, { '_id': 6, 'ticker': 'XYZ', 'hour': 2, 'price': 35 }, { '_id': 7, 'ticker': 'XYZ', 'hour': 3, 'price': 25 } ]) window_result = list(stock_prices.aggregate([ { '$setWindowFields': { 'partitionBy': '$ticker', 'sortBy': { 'hour': 1 }, 'output': { 'firstTwoSoFar': { '$firstN': { 'input': '$price', 'n': 2 }, 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) print('Window result:', window_result) finally: client.close() example()