$setOnInsert

noun

say it: “DOL-er SET-on-in-SURT” /ˈdɑlər ˈsɛt ɑn ɪnˈsɝt/

A MongoDB update operator that sets fields only when an upsert creates a new document.

What does $setOnInsert do in a MongoDB update?

$setOnInsert sets its fields only when an upsert creates a new document; when the document already exists, they're left alone. It's how a first-saved date or a starting count is set once.

db.ratings.updateOne(
  { user: "ana", recipeId: 4 },
  { $set: { stars: 5 }, $setOnInsert: { firstRated: new Date() } },
  { upsert: true }
);
// firstRated is set the first time only; stars changes every time

In a sentence

  • “Without $setOnInsert, the upsert would reset the join date each time the profile was saved.”
  • “$setOnInsert stamped firstRated on the first rating and left it alone on every change after.”

Level: Journeyman · More MongoDB terms at this level

Updated