Para agentes de IA: hay un índice de documentación disponible en https://www.mongodb.com/es/docs/llms.txt — versiones en markdown de todas las páginas están disponibles agregando .md a cualquier ruta URL.
Docs Menu

Bulk.find.upsert() (método mongosh)

Tip

MongoDB también proporciona el método Mongo.bulkWrite() para realizar operaciones de guardar masiva.

Bulk.find.upsert()

Establece la opción de inserción en verdadero para una operación de actualización o reemplazo y tiene la siguiente sintaxis:

Bulk.find(<query>).upsert().update(<update>);
Bulk.find(<query>).upsert().updateOne(<update>);
Bulk.find(<query>).upsert().replaceOne(<replacement>);

Con la opción upsert establecer en true, si no existe ningún documento coincidente para la condición Bulk.find(), la operación de actualización o sustitución realiza una inserción. Si existe un documento coincidente, la operación de actualización o sustitución realiza la actualización o sustitución especificada.

Use Bulk.find.upsert() with the following write operations:

Este comando está disponible en implementaciones alojadas en los siguientes entornos:

  • MongoDB Atlas: El servicio totalmente gestionado para implementaciones de MongoDB en la nube

Nota

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.

The following describe the insert behavior of various write operations when used in conjunction with Bulk.find.upsert().

El método Bulk.find.replaceOne() acepta, como su parámetro, un documento de sustitución que solo contiene pares de campo y valor:

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { item: "abc123" } ).upsert().replaceOne(
{
item: "abc123",
status: "P",
points: 100,
}
);
bulk.execute();

If the replacement operation with the Bulk.find.upsert() option performs an insert, the inserted document is the replacement document. If neither the replacement document nor the query document specifies an _id field, MongoDB adds the _id field:

{
"_id" : ObjectId("52ded3b398ca567f5c97ac9e"),
"item" : "abc123",
"status" : "P",
"points" : 100
}

El método Bulk.find.updateOne() acepta como parámetro ya sea:

Si el parámetro es un documento de reemplazo que contiene solo pares de campo y valor:

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "P" } ).upsert().updateOne(
{
item: "TBD",
points: 0,
inStock: true,
status: "I"
}
);
bulk.execute();

Then, if the update operation with the Bulk.find.upsert() option performs an insert, the inserted document is the replacement document. If neither the replacement document nor the query document specifies an _id field, MongoDB adds the _id field:

{
"_id" : ObjectId("52ded5a898ca567f5c97ac9f"),
"item" : "TBD",
"points" : 0,
"inStock" : true,
"status" : "I"
}

Si el parámetro es un documento de actualización que contiene únicamente expresiones de operadores de actualización:

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "P", item: null } ).upsert().updateOne(
{
$setOnInsert: { qty: 0, inStock: true },
$set: { points: 0 }
}
);
bulk.execute();

Then, if the update operation with the Bulk.find.upsert() option performs an insert, the update operation inserts a document with field and values from the query document of the Bulk.find() method and then applies the specified updates from the update document. If neither the update document nor the query document specifies an _id field, MongoDB adds the _id field:

{
"_id" : ObjectId("5e28d1a1500153bc2872dadd"),
"item" : null,
"status" : "P",
"inStock" : true,
"points" : 0,
"qty" : 0
}

Los métodos de actualización pueden aceptar una pipeline de agregación. Por ejemplo, los siguientes usos:

  • la etapa $replaceRoot que puede proporcionar un comportamiento algo similar al de una expresión de operador de actualización $setOnInsert,

  • la etapa $set que puede proporcionar un comportamiento similar a la expresión del operador de actualización $set,

  • la variable de agregación NOW, que se resuelve en la fecha y hora actual y puede proporcionar un comportamiento similar al de una $currentDate expresión del operador de actualización.

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { item: "Not Found", status: "P" } ).upsert().updateOne(
[
{ $replaceRoot: { newRoot: { $mergeObjects: [ { qty: 0, inStock: true }, "$$ROOT" ] } } },
{ $set: { points: 0, lastModified: "$$NOW" } }
]
);
bulk.execute();

Then, if the update operation with the Bulk.find.upsert() option performs an insert, the update operation inserts a document with field and values from the query document of the Bulk.find() method and then applies the specified aggregation pipeline. If neither the update document nor the query document specifies an _id field, MongoDB adds the _id field:

{
"_id" : ObjectId("5e28cf1e500153bc2872d49f"),
"qty" : 0,
"inStock" : true,
"item" : "Not Found",
"status" : "P",
"points" : 0,
"lastModified" : ISODate("2020-01-22T22:39:26.789Z")
}

When using upsert() with the multiple document update method Bulk.find.update(), if no documents match the query condition, the update operation inserts a single document.

El método Bulk.find.update() acepta como parámetro:

Si el parámetro es un documento de actualización que contiene únicamente expresiones de operadores de actualización:

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "P" } ).upsert().update(
{
$setOnInsert: { qty: 0, inStock: true },
$set: { status: "I", points: "0" }
}
);
bulk.execute();

Then, if the update operation with the Bulk.find.upsert() option performs an insert, the update operation inserts a single document with the fields and values from the query document of the Bulk.find() method and then applies the specified update from the update document. If neither the update document nor the query document specifies an _id field, MongoDB adds the _id field:

{
"_id": ObjectId("52ded81a98ca567f5c97aca1"),
"status": "I",
"qty": 0,
"inStock": true,
"points": "0"
}

Los métodos de actualización pueden aceptar una pipeline de agregación. Por ejemplo, los siguientes usos:

  • la etapa $replaceRoot que puede proporcionar un comportamiento algo similar al de una expresión de operador de actualización $setOnInsert,

  • la etapa $set que puede proporcionar un comportamiento similar a la expresión del operador de actualización $set,

  • la variable de agregación NOW, que se resuelve a la fecha y hora actual y puede proporcionar un comportamiento similar al operador de actualización de la expresión $currentDate. El valor de NOW permanece igual en toda la pipeline. Para acceder a las variables de agregación, antepone la variable con double signos de dólar $$ y enciérrala entre comillas.

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { item: "New Item", status: "P" } ).upsert().update(
[
{ $replaceRoot: { newRoot: { $mergeObjects: [ { qty: 0, inStock: true }, "$$ROOT" ] } } },
{ $set: { points: 0, lastModified: "$$NOW" } }
]
);
bulk.execute();

Then, if the update operation with the Bulk.find.upsert() option performs an insert, the update operation inserts a single document with the fields and values from the query document of the Bulk.find() method and then applies the aggregation pipeline. If neither the update document nor the query document specifies an _id field, MongoDB adds the _id field:

{
"_id" : ObjectId("5e2920a5b4c550aad59d18a1"),
"qty" : 0,
"inStock" : true,
"item" : "New Item",
"status" : "P",
"points" : 0,
"lastModified" : ISODate("2020-01-23T04:27:17.780Z")
}
Califique esta página