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.

  1. Increment the number_of_reviews field of a specific listing by 1 (find one by its id)
  2. Add the field destacado: true to a listing of your choice
  3. Remove the destacado field from the previous listing (use $unset)
  4. Update ALL listings in CIUTAT VELLA adding the field zona: "centro histórico"
  5. Increment the review_scores_rating score of a specific listing by 0.1

Pro:

  1. Rename the name field to titulo in a test listing (use $rename)
  2. Update multiple fields at once: increment number_of_reviews by 1 AND add the field verificado: true to the same listing (use $set and $inc together)
  3. Use $max to ensure that the review_scores_rating score of a listing is at least 4.0 (if it is already higher, it doesn't change)

Solutions

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.