$first - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$first

バージョン 5.0 の新機能。

Elastic クラスターではサポートされていません。

Amazon DocumentDB の $first演算子は、グループ化されたドキュメントセットから最初のドキュメントを返します。集約パイプラインで一般的に使用され、特定の条件に一致する最初のドキュメントを取得します。

パラメータ

  • expression: 各グループの最初の値として返される式。

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

コードの例

$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()