Video Transcript (English)
Hello!
Two ways to update a document in MongoDB are: Update the value of an existing field, or Define a new field and value. Note that this is not an exhaustive list of the available update operations.
For brevity, we’ll assume that the MongoClient and MongoCollection instances have been already initialized.
We use the MongoCollection.updateOne() method when we need to update a single document that matches some specified criteria. The updateOne() method accepts a query filter and an update document.
To demonstrate the updateOne() method, let’s assume that we have bank account documents in an accounts collection, and we need to increase the balance of John Doe’s account by 100. Additionally, we want to add an account status field that shows if the account is active or dormant.
To do this, we’ll define the query and update arguments for the updateOne method.
The query finds John Doe’s account (MDB12234728). The update arguments add an account status field of active and increase John Doe’s balance by 100.
Notice that we’re using the Updates builder class to combine multiple update operators. The builder provides type checking and simplified syntax.
The updateOne() method finds the first document that matches the filter and applies the specified update modifications. It returns an UpdateResult object that includes the number of documents modified, which will be either zero or one.
To update fields with array values, we can use the Update builder’s operators such as Updates.push(), Updates.pull(), Updates.popLast().
To specify elements in an array with positional operators, use dot notation with the positional `$` operator.
Now we’ll demonstrate the updateMany() method, which is used to update multiple documents in a single operation. Just like the updateOne() method, the updateMany() method accepts a query and a combination of updates.
We’ll use the updateMany() method to add a minimum balance field to all savings account documents.
First, we define our query filter and set the minimum_balance field to 100. The query filter searches for all savings accounts. The updates combination adds a minimum balance field of 100 to all savings accounts.
Now that we’ve specified both the query filter and update document, we can invoke the updateMany() method.
Well done!
In this video, we covered how to perform single and multiple document updates. We used a query filter to match the documents to update, and the Updates builder class to define our update operators.