View a markdown version of this page

$minN - Amazon DocumentDB

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

$minN

8.0.1 版中的新内容。

Amazon DocumentDB 中的$minN运算符返回 N 个最小值。当在$group阶段中用作累加器时,它返回每组中 N 个最小值的数组。当用作数组表达式运算符时,它返回数组的最少 N 个元素。

参数

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

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

行为

数组表达式运算符行为

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

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

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

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

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

蓄能器行为

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

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

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

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

输出排序

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

示例(MongoDB Shell)

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

创建示例文档

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", lowestTwo: { $minN: { input: "$score", n: 2 } } } } ]);

输出

[ { "_id": "math", "lowestTwo": [72, 68] }, { "_id": "science", "lowestTwo": [78, 65] } ]

表达式用法示例(MongoDB Shell)

该$minN运算符也可以用作$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: { lowestThree: { $minN: { input: "$values", n: 3 } } }} ]);

输出

[ { "_id": 1, "lowestThree": [45, 12, 3] }, { "_id": 2, "lowestThree": [44, 23, 11] } ]

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

8.0.2 版中的新内容。

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

注意

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

输出

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

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

代码示例

要查看使用$minN运算符的代码示例,请选择要使用的语言的选项卡。以下示例显示累加器的用法 (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 smallest 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", lowestTwo: { $minN: { input: "$score", n: 2 } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Expression usage: N smallest 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: { lowestThree: { $minN: { input: "$values", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); // Window operator usage: N smallest 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: { lowestTwoSoFar: { $minN: { 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 smallest 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', 'lowestTwo': { '$minN': { 'input': '$score', 'n': 2 } } } } ])) print('Accumulator result:', accumulator_result) # Expression usage: N smallest 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': { 'lowestThree': { '$minN': { 'input': '$values', 'n': 3 } } } } ])) print('Expression result:', expression_result) # Window operator usage: N smallest 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': { 'lowestTwoSoFar': { '$minN': { 'input': '$price', 'n': 2 }, 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) print('Window result:', window_result) finally: client.close() example()