View a markdown version of this page

$maxN - Amazon DocumentDB

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

$maxN

8.0.1 版中的新内容。

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

参数

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

  • n:解析为正整数的表达式,用于指定要返回的最大值的数量。

行为

数组表达式运算符行为

  • 您不能指定n小于的值1。

  • $maxN过滤掉input数组中找到的null值。

  • 如果指定的值大n于或等于数组中元素的数量,则$maxN返回input数组中的input所有元素。

  • 如果input解析为非数组值,则聚合操作出错。

  • 如果同时input包含数字和字符串元素,则根据 BSON 比较顺序在数字元素之前对字符串元素进行排序。

蓄能器行为

  • 当用作累加器时,n必须是正整数表达式,该表达式要么是常数,要么取决于的_id值。$group

  • $maxN过滤掉空值和缺失值。

  • 如果该组包含的元素少于n元素,则$maxN返回该组中的所有元素。

  • $maxN按照 BSON 比较顺序比较输入数据,以确定相应的输出类型。当输入数据包含多个数据类型时,$maxN输出类型是比较顺序中最高的。

输出排序

$maxN不按特定的排序顺序返回值。如果要求保证特定的排序顺序,则$topN改用或将结果包装为$sortArray。

示例(MongoDB Shell)

以下示例说明如何使用$maxN累加器检索每个科目的两个最高分数。

创建示例文档

db.scores.insertMany([ { subject: "math", score: 85 }, { subject: "math", score: 72 }, { subject: "math", score: 93 }, { subject: "math", score: 68 }, { subject: "science", score: 90 }, { subject: "science", score: 78 }, { subject: "science", score: 65 }, { subject: "science", score: 88 } ]);

查询示例

db.scores.aggregate([ { $group: { _id: "$subject", highestTwo: { $maxN: { input: "$score", n: 2 } } } } ]);

输出

[ { "_id": "math", "highestTwo": [85, 93] }, { "_id": "science", "highestTwo": [88, 90] } ]

表达式用法示例(MongoDB Shell)

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

创建示例文档

db.readings.insertMany([ { _id: 1, sensor: "A", values: [45, 12, 78, 3, 56] }, { _id: 2, sensor: "B", values: [90, 23, 67, 11, 44] } ]);

查询示例

db.readings.aggregate([ { $project: { highestThree: { $maxN: { input: "$values", n: 3 } } }} ]);

输出

[ { "_id": 1, "highestThree": [45, 56, 78] }, { "_id": 2, "highestThree": [44, 90, 67] } ]

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

8.0.2 版中的新内容。

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

注意

在中用作窗口运算符时$setWindowFields,中间数据限制$maxN为 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: { highestTwoSoFar: { $maxN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]);

输出

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

每个文档都使用highestTwoSoFar其窗口内的两个最大price值进行扩展。如输出排序部分所述,不能保证返回数组中值的顺序。

代码示例

要查看使用$maxN运算符的代码示例,请选择要使用的语言的选项卡。以下示例显示累加器的用法 (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: N largest values per group const scores = db.collection('scores'); await scores.insertMany([ { subject: "math", score: 85 }, { subject: "math", score: 72 }, { subject: "math", score: 93 }, { subject: "math", score: 68 }, { subject: "science", score: 90 }, { subject: "science", score: 78 }, { subject: "science", score: 65 }, { subject: "science", score: 88 } ]); const accumulatorResult = await scores.aggregate([ { $group: { _id: "$subject", highestTwo: { $maxN: { input: "$score", n: 2 } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Expression usage: N largest elements from an array field const readings = db.collection('readings'); await readings.insertMany([ { _id: 1, sensor: "A", values: [45, 12, 78, 3, 56] }, { _id: 2, sensor: "B", values: [90, 23, 67, 11, 44] } ]); const expressionResult = await readings.aggregate([ { $project: { highestThree: { $maxN: { input: "$values", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); // Window operator usage: N largest 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: { highestTwoSoFar: { $maxN: { input: "$price", n: 2 }, window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); } 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: N largest values per group scores = db['scores'] scores.insert_many([ { 'subject': 'math', 'score': 85 }, { 'subject': 'math', 'score': 72 }, { 'subject': 'math', 'score': 93 }, { 'subject': 'math', 'score': 68 }, { 'subject': 'science', 'score': 90 }, { 'subject': 'science', 'score': 78 }, { 'subject': 'science', 'score': 65 }, { 'subject': 'science', 'score': 88 } ]) accumulator_result = list(scores.aggregate([ { '$group': { '_id': '$subject', 'highestTwo': { '$maxN': { 'input': '$score', 'n': 2 } } } } ])) print('Accumulator result:', accumulator_result) # Expression usage: N largest elements from an array field readings = db['readings'] readings.insert_many([ { '_id': 1, 'sensor': 'A', 'values': [45, 12, 78, 3, 56] }, { '_id': 2, 'sensor': 'B', 'values': [90, 23, 67, 11, 44] } ]) expression_result = list(readings.aggregate([ { '$project': { 'highestThree': { '$maxN': { 'input': '$values', 'n': 3 } } } } ])) print('Expression result:', expression_result) # Window operator usage: N largest 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': { 'highestTwoSoFar': { '$maxN': { 'input': '$price', 'n': 2 }, 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) print('Window result:', window_result) finally: client.close() example()