翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$first
バージョン 5.0 の新機能。
Elastic クラスターではサポートされていません。
Amazon DocumentDB の $first演算子は、グループ化されたドキュメントセットから最初のドキュメントを返します。集約パイプラインで一般的に使用され、特定の条件に一致する最初のドキュメントを取得します。
パラメータ
例 (MongoDB シェル)
次の例は、 $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 シェル)
バージョン 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()