本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$min
$min 運算子會從值陣列傳回最小值。它可用於彙總階段,以尋找跨多個文件指定欄位的最小值。
參數
範例 (MongoDB Shell)
下列範例示範 $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()