In this post I’m going to look at the different ways we can update documents within a MongoDB collection.
In the collection I’m going to update is three documents each with
Updating the Whole Document
Here is the document we’re going to update.
If we do an update like the one below we replace the whole of the document rather than just updating the name and gender fields we’ve specified values for .
Updating a Field
In order to just update an individual field or set of fields we need to use the $set operator in our update command. Here is the document before the update.
I’m going to add a gender field with the value “female”.
Removing a Field
We can use the $unset command to remove the gender field.
There are lots of different operators for updating fields with array values. We can add an individual value using the $push operator.
$pop can be used to remove a value at the start or the end of an array. Supply 1 removes the last value.
-1 removes the first value.
$pushAll allows us to add multiple values provided as an array.
$pull allows us to remove a specific value.
$pullAll allows us to remove multiple values. $addToSet treats the array like a set only adding a value if it is unique. The first time we call the command the array does not contain “sausages” so it is added. The second time it does so the array is left unchanged.
Compare this to using the $push operator which adds “sausages” even though it already exists.
We can update a specific array element using the $set operator and dot notation. array access begins at 0.
There may be occasions when you don’t know if a document exists or not. We can supply a third parameter to the update function. This is the upsert flag. If we set it to true it means the document will be created if it does not exist or updated if it does. In the example below the first time we issue the update command their is no matching document so it is inserted. The second time there is so the existing document is updated.
Updating Multiple Documents
By default an update command will only update one document. If your criteria matches multiple documents the document updated will be selected at random.
Adding in a forth parameter to the update command and setting it to true, sets the multi flag and means that all matching documents are updated.
That completes my brief look at updates in MongoDB. In my final blog on CRUD in MongoDB I’ll look at removing documents from a collection.