Search code examples
mongodbbulkupdate

bulk update based on changing find/query in mongodb


In MongoDB, I know it's possible to do a bulk update like this:

bulk.find( { status: "D" } ).update( { $set: { status: "I", points: "0" } } );

This will match all documents with a "status" of "D".

Is it possible to execute a similar operation where the find part is always changing?

In other words, can I do this all in one operation?

bulk.find( { status: "A" } ).update( { $set: { status: "X", points: "1" } } );
bulk.find( { status: "B" } ).update( { $set: { status: "Y", points: "2" } } );
bulk.find( { status: "C" } ).update( { $set: { status: "Z", points: "3" } } );

Solution

  • Yes of course it is possible, as well as being largely the point of Bulk() operations in general.

    What is actually happening in your listing:

    bulk.find( { status: "A" } ).update( { $set: { status: "X", points: "1" } } );
    bulk.find( { status: "B" } ).update( { $set: { status: "Y", points: "2" } } );
    bulk.find( { status: "C" } ).update( { $set: { status: "Z", points: "3" } } );
    

    Is that the operations are actually being "queued" or "batched" in an instruction that has yet to be executed on the server.

    Only when you actually invoke the instruction are the operations sent to and performed on the server:

    bulk.execute()
    

    The response will contain the results from the operations and possibly any errors depending on whether initializeOrderedBulkOp() or initializeUnonderedBulkOp() was the action that was called to initialize the bulk actions.

    Note that once .execute() has been called then you need to re-initialize before adding further operations and calling .execute() again as it will effectively "drain" the queue of operations.