Lesson 15 +10 XP

Field Update Operators

Field Update Operators

Update operators modify documents during updateOne() and updateMany(). These change individual fields.

The field operators

OperatorMeaning
$currentDateSets a field to the current date
$incIncrements a numeric field
$renameRenames a field
$setSets a field's value
$unsetRemoves a field from the document

Using them

// Set likes to 2
db.posts.updateOne({ title: "Post Title 1" }, { $set: { likes: 2 } })

// Increment likes by 1
db.posts.updateMany({}, { $inc: { likes: 1 } })

// Rename the "likes" field to "stars"
db.posts.updateMany({}, { $rename: { likes: "stars" } })

// Remove the "category" field
db.posts.updateMany({}, { $unset: { category: "" } })

// Set lastUpdated to the current time
db.posts.updateMany({}, { $currentDate: { lastUpdated: true } })

$set vs $inc

  • $set replaces a field's value with whatever you give it.
  • $inc adds a number to an existing numeric field. So { $inc: { likes: 1 } } adds 1, while { $set: { likes: 1 } } forces it to exactly 1.

TL;DR

  • $set assigns, $inc increments, $unset removes.
  • $rename renames a field; $currentDate stamps the current time.