Updating Documents

πŸ“Œ updateOne()

updateOne will only update the first one that matches the filter

db.movieDetails.updateOne({"title": "The Martian"},{$set: {"poster": "new url"}})
  • First, specify the filter.

  • Second, specify the β€œhow”.

$set operator uses a document as an argument and uses all the key values from the document to update the document that matches the filter.

πŸ€“ Update Operators

Official documentation: https://docs.mongodb.com/manual/reference/operator/update/#id1​

For scalar values

  • $set, Sets the value of a field in a document.

  • $unset, Removes the specified field from a document.

  • $inc, increment a value by the specified value to a field

For array values

  • $pop, $pull, $pullAll,

  • $push creates an array if this does not already exist, each is a modifier to use every element as an independent element for the array.

πŸ“Œ updateMany()

Will make the same modification to all documents that match the filter.

db.movieDetails.updateMany({"rated": null },{$unset: {"rated": ""}})

$unset operator will remove all the values that match the filter.

πŸ€“ Upserts

Update documents that match the filter if there are none insert the update document as a new document in the collection.

db.movieDetails.updateOne({ "imdb.id": detail.imdb.id }, 
{ $set: detail }, 
{ Upsert: true });

Here you are using a variable called detail that has a document’s detail.

The upsert word is a keyword, executed when trying to update a document and you do not find it, you insert one instead.

πŸ“Œ replaceOne()

db.movieDetails.replaceOne(filter, doc);

Variables: filter, doc

At mongodb shell (a javascript interpreter :o) define filter variable.

let filter = {"title": "House, M,D., Season Four: New Beginnings"}
let doc = db.movieDetails.findOne(filter)

The doc variable will get one document that matches the filter conditions. Now modify the doc variable, to add a genre and a poster field.

πŸ’‘ Note: this method will only replace the first document it finds.

Last updated