Dica
O MongoDB também fornece o método db.collection.bulkWrite() para executar operações de gravação em massa.
Definição
db.collection.initializeOrderedBulkOp()Importante
Método mongosh
This page documents a
mongoshmethod. This is not the documentation for a language-specific driver, such as Node.js.Para drivers de API do MongoDB, consulte a documentação do driver do MongoDB específica da linguagem.
Inicializa e retorna um novo construtor de operações do
Bulk()para uma coleção. O construtor constrói uma lista ordenada de operações de gravação que MongoDB executa em massa.Retorna: novo objeto de construtor de operações
Bulk().
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
Ordem de operação
Com uma lista de operações ordenadas, o MongoDB executa as operações de gravação na lista serialmente.
Execução de operações
When executing an ordered list of operations, MongoDB groups the operations by the operation type and contiguity; i.e. contiguous operations of the same type are grouped together. For example, if an ordered list has two insert operations followed by an update operation followed by another insert operation, MongoDB groups the operations into three separate groups: first group contains the two insert operations, second group contains the update operation, and the third group contains the last insert operation. This behavior is subject to change in future versions.
Bulk() operations in mongosh and comparable methods in the drivers do not have a limit for the number of operations in a group. To see how the operations are grouped for bulk operation execution, call Bulk.getOperations() after the execution.
Executing an ordered list of operations on a sharded collection will generally be slower than executing an unordered list since with an ordered list, each operation must wait for the previous operation to finish.
Error Handling
Se ocorrer um erro durante o processamento de uma das operações de gravação, o MongoDB retornará sem processar as operações de gravação restantes na lista.
Exemplos
O seguinte inicializa um construtor de operações Bulk() na users collection, adiciona uma série de operações de gravação e executa as operações:
var bulk = db.users.initializeOrderedBulkOp(); bulk.insert( { user: "abc123", status: "A", points: 0 } ); bulk.insert( { user: "ijk123", status: "A", points: 0 } ); bulk.insert( { user: "mop123", status: "P", points: 0 } ); bulk.find( { status: "D" } ).delete(); bulk.find( { status: "P" } ).update( { $set: { comment: "Pending" } } ); bulk.execute();