View a markdown version of this page

$first - Amazon DocumentDB

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

$first

Novo na versão 5.0.

Não é compatível com o cluster elástico.

O $first operador no Amazon DocumentDB retorna o primeiro documento de um conjunto agrupado de documentos. É comumente usado em pipelines de agregação para recuperar o primeiro documento que corresponda a uma condição específica.

Parâmetros

  • expression: a expressão a ser retornada como o primeiro valor em cada grupo.

Exemplo (MongoDB Shell)

O exemplo a seguir demonstra o uso do $first operador para recuperar o valor do primeiro item encontrado para cada categoria durante a agregação.

Nota: $first retorna o primeiro documento com base na ordem atual dos documentos no pipeline. Para garantir um pedido específico (por exemplo, por data, preço etc.), um $sort estágio deve ser usado antes do $group estágio.

Crie documentos de amostra

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" } ]);

Exemplo de consulta

db.products.aggregate([ { $group: { _id: "$category", firstItem: { $first: "$item" } } } ]);

Saída

[ { "_id" : "food", "firstItem" : "abc" }, { "_id" : "toy", "firstItem" : "xyz" } ]

Exemplo de uso do operador de janela (MongoDB Shell)

Novo na versão 8.0.2.

O $first operador também pode ser usado como operador de janela no $setWindowFields palco. Nesse contexto, ele retorna o valor expression do primeiro documento em cada janela. Você especifica o operador no output campo e, opcionalmente, define os limites da janela com um window documento.

nota

Quando usado como operador de janela em$setWindowFields, $first é limitado a 100 MB de dados intermediários. Uma operação que excede esse limite retorna um erro.

Crie documentos de amostra

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 } ]);

Exemplo de consulta

O exemplo a seguir particiona os documentos porticker, classifica cada partição por hour e retorna o primeiro preço (mais antigo) registrado em cada partição.

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

Saída

[ { "_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 } ]

Cada documento é aumentado com firstPrice o preço do primeiro documento em sua janela (o mais antigo hour na partição).

Exemplos de código

Para ver um exemplo de código para usar o $first operador, escolha a guia do idioma que você deseja usar. Os exemplos a seguir mostram o uso do acumulador (em$group) e o uso do operador de janela (em$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()