View a markdown version of this page

$first - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$first

5.0 版的新功能。

Elastic 叢集不支援。

Amazon DocumentDB 中的$first運算子會從一組分組的文件中傳回第一個文件。它通常用於彙總管道,以擷取符合特定條件的第一個文件。

參數

  • expression:傳回為每個群組中第一個值的表達式。

範例 (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" } ]

視窗運算子用量範例 (MongoDB Shell)

8.0.2 版的新功能。

該$first運算子也可以用作$setWindowFields階段中的視窗運算子。在這種情況下,它會expression傳回每個視窗中第一個文件的 值。您可以在 output 欄位下指定運算子,並選擇性地使用window文件定義視窗邊界。

注意

在 中用作視窗運算子時$setWindowFields, 限制$first為 100 MB 的中繼資料。超過此限制的操作會傳回錯誤。

建立範例文件

db.stockPrices.insertMany([ { _id: 1, ticker: "ABC", hour: 1, price: 50 }, { _id: 2, ticker: "ABC", hour: 2, price: 45 }, { _id: 3, ticker: "ABC", hour: 3, price: 60 }, { _id: 4, ticker: "ABC", hour: 4, price: 40 }, { _id: 5, ticker: "XYZ", hour: 1, price: 30 }, { _id: 6, ticker: "XYZ", hour: 2, price: 35 }, { _id: 7, ticker: "XYZ", hour: 3, price: 25 } ]);

查詢範例

下列範例會依 分割文件ticker、依 排序每個分割區hour,並傳回每個分割區中記錄的第一個 (最早) 價格。

db.stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { firstPrice: { $first: "$price", window: { documents: ["unbounded", "current"] } } } } } ]);

輸出

[ { "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "firstPrice": 50 }, { "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "firstPrice": 50 }, { "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "firstPrice": 50 }, { "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "firstPrice": 50 }, { "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "firstPrice": 30 }, { "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "firstPrice": 30 }, { "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "firstPrice": 30 } ]

每個文件都會以 擴增firstPrice,這是其視窗中第一個文件的價格 (分割區hour中最早的文件)。

程式碼範例

若要檢視使用 $first 運算子的程式碼範例,請選擇您要使用的語言標籤。下列範例顯示累積器用量 (在 中$group) 和視窗運算子用量 (在 中$setWindowFields):

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'); // Accumulator usage: first value per group const products = db.collection('products'); await 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" } ]); const accumulatorResult = await products.aggregate([ { $group: { _id: "$category", firstItem: { $first: "$item" } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Window operator usage: first value within each partition const stockPrices = db.collection('stockPrices'); await stockPrices.insertMany([ { _id: 1, ticker: "ABC", hour: 1, price: 50 }, { _id: 2, ticker: "ABC", hour: 2, price: 45 }, { _id: 3, ticker: "ABC", hour: 3, price: 60 }, { _id: 4, ticker: "ABC", hour: 4, price: 40 }, { _id: 5, ticker: "XYZ", hour: 1, price: 30 }, { _id: 6, ticker: "XYZ", hour: 2, price: 35 }, { _id: 7, ticker: "XYZ", hour: 3, price: 25 } ]); const windowResult = await stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { firstPrice: { $first: "$price", window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); } 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'] # Accumulator usage: first value per group products = db['products'] products.insert_many([ { '_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' } ]) accumulator_result = list(products.aggregate([ { '$group': { '_id': '$category', 'firstItem': { '$first': '$item' } } } ])) pprint(accumulator_result) # Window operator usage: first value within each partition stock_prices = db['stockPrices'] stock_prices.insert_many([ { '_id': 1, 'ticker': 'ABC', 'hour': 1, 'price': 50 }, { '_id': 2, 'ticker': 'ABC', 'hour': 2, 'price': 45 }, { '_id': 3, 'ticker': 'ABC', 'hour': 3, 'price': 60 }, { '_id': 4, 'ticker': 'ABC', 'hour': 4, 'price': 40 }, { '_id': 5, 'ticker': 'XYZ', 'hour': 1, 'price': 30 }, { '_id': 6, 'ticker': 'XYZ', 'hour': 2, 'price': 35 }, { '_id': 7, 'ticker': 'XYZ', 'hour': 3, 'price': 25 } ]) window_result = list(stock_prices.aggregate([ { '$setWindowFields': { 'partitionBy': '$ticker', 'sortBy': { 'hour': 1 }, 'output': { 'firstPrice': { '$first': '$price', 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) pprint(window_result) except Exception as e: print(f"An error occurred: {e}") finally: if client: client.close() example()