A partir de MongoDB 4.4, $merge puede dar salida a la misma colección que se está agregando:
db.products.aggregate([
{ /**
* from: The target collection.
* localField: The local join field.
* foreignField: The target join field.
* as: The name for the results.
* pipeline: The pipeline to run on the joined collection.
* let: Optional variables to use in the pipeline field stages.
*/
$lookup: {
from: 'events',
localField: '_id',
foreignField: 'product_id',
as: 'events'
}},
{/**
* into: The target collection.
* on: Fields to identify.
* whenMatched: Action for matching docs.
* whenNotMatched: Action for non-matching docs.
*/
$merge: {
into: 'products',
on: "_id",
whenMatched: 'merge',
whenNotMatched: 'insert'
}}
])
Tenga en cuenta: cuando $merge genera la misma colección que se está agregando, los documentos pueden actualizarse varias veces o la operación puede generar un bucle infinito. Más detalles aquí https://docs .mongodb.com/manual/reference/operator/aggregation/merge/#merge-behavior-same-collection
Si se trata de una actualización única, puede salvaguardar la canalización agregando un filtro inicial como primera etapa para garantizar que un documento se actualice exactamente una vez:
{ $match: { events: { $exists: false } }