本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$min
运$min算符返回值数组中的最小值。它可以在聚合阶段用于在多个文档中查找指定字段的最小值。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$min运算符在多个文档中查找该age字段的最小值。
创建示例文档
db.users.insertMany([
{ name: "John", age: 35 },
{ name: "Jane", age: 28 },
{ name: "Bob", age: 42 },
{ name: "Alice", age: 31 }
]);
查询示例
db.users.aggregate([
{ $group: { _id: null, minAge: { $min: "$age" } } },
{ $project: { _id: 0, minAge: 1 } }
])
输出
[ { minAge: 28 } ]
代码示例
要查看使用该$min命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function findMinAge() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const users = db.collection('users');
const result = await users.aggregate([
{ $group: {
_id: null,
minAge: { $min: "$age" }
}}
]).toArray();
console.log(result);
client.close();
}
findMinAge();
- Python
-
from pymongo import MongoClient
def find_min_age():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db.users
result = list(users.aggregate([
{ "$group": {
"_id": None,
"minAge": { "$min": "$age" }
}}
]))
print(result)
client.close()
find_min_age()