View a markdown version of this page

$first - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$first

5.0 版中的新增内容。

弹性集群不支持。

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