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

代码示例

要查看使用$maxN运算符的代码示例,请选择要使用的语言的选项卡。以下示例显示了累加器的用法(输入$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: N largest values per group const scores = db.collection('scores'); 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'); const expressionResult = await readings.aggregate([ { $project: { highestThree: { $maxN: { input: "$values", 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: N largest values per group scores = db['scores'] 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'] expression_result = list(readings.aggregate([ { '$project': { 'highestThree': { '$maxN': { 'input': '$values', 'n': 3 } } } } ])) print('Expression result:', expression_result) finally: client.close() example()