在MongoDB中,可以使用$min
操作符来查询集合中的最小值。
语法如下:
db.collection.aggregate([
{
$group: {
_id: null,
minValue: { $min: "$fieldName" }
}
}
])
其中,collection
是要查询的集合的名称,fieldName
是要计算最小值的字段名称。
以下是一个示例,假设有一个名为students
的集合,其中包含name
和age
字段。要查询age
字段的最小值:
db.students.aggregate([
{
$group: {
_id: null,
minValue: { $min: "$age" }
}
}
])
查询结果将以如下形式返回:
{ "_id" : null, "minValue" : 18 }
上述查询返回了age
字段的最小值18。