7. Updating documents
Now you will learn how to modify existing documents using update operators.
Updating a document
To update a single document use updateOne:
db.listings.updateOne(
{ name: "My apartment in Barcelona" },
{ $set: { price: "$80.00" } }
)
The first parameter is the filter (which documents to update). The second is the update (what to change).
Important: always use operators like $set, $inc, etc. If you don't, you will replace the entire document.
Updating multiple documents
To update all documents that match a filter use updateMany:
// Adds a field to all listings in EXTRAMURS
db.listings.updateMany(
{ neighbourhood_group_cleansed: "EXTRAMURS" },
{ $set: { zona: "norte" } }
)
Replacing a document
To completely replace a document use replaceOne:
db.listings.replaceOne(
{ name: "My apartment in Barcelona" },
{
name: "My renovated apartment",
neighbourhood_group_cleansed: "EIXAMPLE",
room_type: "Entire home/apt",
accommodates: 6,
price: "$120.00"
}
)
This removes all the old fields and replaces them with the new ones. Use it carefully.
Update operators
The most common operators:
$set: sets the value of a field
db.unicorns.updateOne(
{ name: 'Aurora' },
{ $set: { weight: 470 } }
)
$unset: removes a field from the document
db.unicorns.updateOne(
{ name: 'Aurora' },
{ $unset: { vampires: "" } }
)
$inc: increments (or decrements) a numeric value
// Increments vampires by 2
db.unicorns.updateOne(
{ name: 'Aurora' },
{ $inc: { vampires: 2 } }
)
// Decrements vampires by 5
db.unicorns.updateOne(
{ name: 'Horny' },
{ $inc: { vampires: -5 } }
)
$min: updates only if the new value is smaller
db.scores.updateOne(
{ _id: 1 },
{ $min: { lowScore: 150 } }
)
$max: updates only if the new value is larger
db.scores.updateOne(
{ _id: 1 },
{ $max: { highScore: 1000 } }
)
$rename: renames a field
db.users.updateOne(
{ name: 'Ana' },
{ $rename: { 'name': 'fullName' } }
)
Operators for arrays
$push: adds an element to the end of an array
db.unicorns.updateOne(
{ name: 'Aurora' },
{ $push: { loves: 'sugar' } }
)
$pull: removes all occurrences of a value from the array
db.unicorns.updateOne(
{ name: 'Aurora' },
{ $pull: { loves: 'carrot' } }
)
$addToSet: adds an element only if it doesn't exist (no duplicates)
db.unicorns.updateOne(
{ name: 'Aurora' },
{ $addToSet: { loves: 'apple' } }
)
Upsert
An upsert updates a document if it exists, or inserts it if it doesn't exist. It is very useful for counters or event logs.
db.hits.updateOne(
{ page: 'unicorns' },
{ $inc: { hits: 1 } },
{ upsert: true }
)
The first time, since the document doesn't exist, it creates it with hits: 1. The following times, it increments the counter.
Updating multiple documents
By default, updateOne only updates the first document it finds. To update all matching ones, use updateMany:
// Vaccinates ALL the unicorns
db.unicorns.updateMany(
{},
{ $set: { vaccinated: true } }
)
Activity 1
Important note: Since we are working with real data, practice first with specific listings before making massive changes.
- Increment the
number_of_reviewsfield of a specific listing by 1 (find one by itsid) - Add the field
destacado: trueto a listing of your choice - Remove the
destacadofield from the previous listing (use$unset) - Update ALL listings in CIUTAT VELLA adding the field
zona: "centro histórico" - Increment the
review_scores_ratingscore of a specific listing by 0.1
Pro:
- Rename the
namefield totituloin a test listing (use$rename) - Update multiple fields at once: increment
number_of_reviewsby 1 AND add the fieldverificado: trueto the same listing (use$setand$inctogether) - Use
$maxto ensure that thereview_scores_ratingscore of a listing is at least 4.0 (if it is already higher, it doesn't change)
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python
The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.
Buy the bookHelp me keep writing
Every coffee gives me a push toward the next article.
Sure, it's on me!
Comments
There are no comments yet.