本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$first
5.0 版的新功能。
Elastic 叢集不支援。
Amazon DocumentDB 中的$first運算子會從一組分組的文件中傳回第一個文件。它通常用於彙總管道,以擷取符合特定條件的第一個文件。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $first運算子來擷取彙總期間針對每個類別遇到的第一個項目值。
注意: 會根據管道中文件的目前順序$first傳回第一個文件。為了確保特定訂單 (例如,依日期、價格等),階段$sort應該在$group階段之前使用。
建立範例文件
db.products.insertMany([
{ _id: 1, item: "abc", price: 10, category: "food" },
{ _id: 2, item: "jkl", price: 20, category: "food" },
{ _id: 3, item: "xyz", price: 5, category: "toy" },
{ _id: 4, item: "abc", price: 5, category: "toy" }
]);
查詢範例
db.products.aggregate([
{ $group: { _id: "$category", firstItem: { $first: "$item" } } }
]);
輸出
[
{ "_id" : "food", "firstItem" : "abc" },
{ "_id" : "toy", "firstItem" : "xyz" }
]
程式碼範例
若要檢視使用 $first命令的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db('test');
const collection = db.collection('products');
const result = await collection.aggregate([
{ $group: { _id: "$category", firstItem: { $first: "$item" } } }
]).toArray();
console.log(result);
} catch (error) {
console.error('Error:', error);
} finally {
await client.close();
}
}
example();
- Python
-
from pymongo import MongoClient
from pprint import pprint
def example():
client = None
try:
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['products']
result = list(collection.aggregate([
{ '$group': { '_id': '$category', 'firstItem': { '$first': '$item' } } }
]))
pprint(result)
except Exception as e:
print(f"An error occurred: {e}")
finally:
if client:
client.close()
example()