View a markdown version of this page

$first - Amazon DocumentDB

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

$first

Nuevo a partir de la versión 5.0.

Elastic Cluster no lo admite.

El $first operador de Amazon DocumentDB devuelve el primer documento de un conjunto de documentos agrupados. Se utiliza habitualmente en las canalizaciones de agregación para recuperar el primer documento que coincide con una condición específica.

Parámetros

  • expression: la expresión que se devuelve como primer valor de cada grupo.

Ejemplo (MongoDB Shell)

El siguiente ejemplo demuestra el uso del $first operador para recuperar el primer valor de elemento encontrado para cada categoría durante la agregación.

Nota: $first devuelve el primer documento según el orden actual de los documentos en proceso. Para garantizar un orden específico (por ejemplo, por fecha, precio, etc.), se debe utilizar una $sort fase antes de la $group fase.

Cree documentos de muestra

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

Ejemplo de consulta

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

Salida

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

Ejemplo de uso de un operador de ventana (MongoDB Shell)

Nuevo a partir de la versión 8.0.2.

El $first operador también se puede utilizar como operador de ventanas en el $setWindowFields escenario. En este contexto, devuelve el valor del expression del primer documento de cada ventana. Especifique el operador en el output campo y, si lo desea, defina los límites de la ventana con un window documento.

nota

Cuando se usa como operador de ventana en$setWindowFields, $first está limitado a 100 MB de datos intermedios. Una operación que supera este límite devuelve un error.

Crea documentos de muestra

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

Ejemplo de consulta

En el ejemplo siguiente se dividen los documentosticker, se ordenan las hour particiones y se devuelve el primer precio (el más antiguo) registrado en cada partición.

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

Salida

[ { "_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 se complementa con firstPrice el precio del primer documento de su ventana (el primero hour de la partición).

Ejemplos de código

Para ver un ejemplo de código sobre el uso $first del operador, seleccione la pestaña correspondiente al idioma que desee utilizar. Los siguientes ejemplos muestran tanto el uso del acumulador (en$group) como el uso del operador de ventanas (en$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()