Dica
O MongoDB também fornece o método db.collection.bulkWrite() para executar operações de gravação em massa.
Descrição
Bulk.find.upsert()Define a opção upsert como true para uma atualização ou uma operação de substituição e tem a seguinte sintaxe:
Bulk.find(<query>).upsert().update(<update>); Bulk.find(<query>).upsert().updateOne(<update>); Bulk.find(<query>).upsert().replaceOne(<replacement>); Com a opção
upsertdefinida comotrue, se não existirem documentos correspondentes para a condiçãoBulk.find(), a operação de atualização ou substituição executará uma inserção. Se houver um documento correspondente, a operação de atualização ou substituição executará a atualização ou substituição especificada.Use
Bulk.find.upsert()with the following write operations:
Compatibilidade
Esse comando está disponível em implantações hospedadas nos seguintes ambientes:
- MongoDB Atlas: o serviço totalmente gerenciado para implantações do MongoDB na nuvem
Observação
Este comando é aceito em todos os clusters do MongoDB Atlas. Para obter informações sobre o suporte do Atlas a todos os comandos, consulte Comandos não suportados.
Comportamento
The following describe the insert behavior of various write operations when used in conjunction with Bulk.find.upsert().
Inserir para Bulk.find.replaceOne()
O método Bulk.find.replaceOne() aceita, como parâmetro, um documento de substituição que contém apenas pares de campos e valores:
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 }
Inserir para Bulk.find.updateOne()
O método Bulk.find.updateOne() aceita como seu parâmetro:
um documento de substituição que contém apenas pares de campos e valores (iguais aos
Bulk.find.replaceOne()),um documento de atualização que contém apenas expressões de operadores de atualização ou
um pipeline de agregação.
Pares de campo e valor
Se o parâmetro for um documento de substituição que contenha apenas pares de campos e valores:
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" }
Atualizar expressões do operador
Se o parâmetro for um documento de atualização que contenha apenas expressões de operador de atualização:
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 }
Pipeline de agregação
Os métodos de atualização podem aceitar um pipeline de agregação. Por exemplo, os seguintes usos:
o estágio
$replaceRootque pode proporcionar um comportamento semelhante ao de uma expressão do operador de atualização$setOnInsert,A variável de agregação
NOW, que produz a data/hora atual e pode fornecer comportamento semelhante a uma expressão de operador de atualização$currentDate.
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") }
Inserir para Bulk.find.update()
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.
O método Bulk.find.update() aceita como seu parâmetro:
um documento de atualização que contém apenas expressões de operadores de atualização ou
um pipeline de agregação.
Atualizar expressões do operador
Se o parâmetro for um documento de atualização que contenha apenas expressões de operador de atualização:
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" }
Pipeline de agregação
Os métodos de atualização podem aceitar um pipeline de agregação. Por exemplo, os seguintes usos:
o estágio
$replaceRootque pode proporcionar um comportamento semelhante ao de uma expressão do operador de atualização$setOnInsert,a variável de agregação
NOW, que produz a data e hora atual e pode fornecer um comportamento semelhante à expressão do operador de atualização$currentDate. O valor deNOWpermanece o mesmo em todo o pipeline. Para acessar variáveis de agregação, prefixe a variável com cifrões duplos$$e coloque entre aspas.
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") }