replaceOne

noun

say it: “rih-PLAYS WUN” /rɪˈpleɪs ˈwʌn/

A MongoDB method that replaces a whole matching document with a new one, keeping only its _id.

What does replaceOne do?

replaceOne swaps the first matching document for a whole new version, keeping only its _id. Any field the new version leaves out is gone, so it's for saving a complete edited document, not for changing one field.

db.recipes.replaceOne(
  { _id: 9 },
  { name: "Garlic Toast", minutes: 5, tags: ["quick"] }
);
// { matchedCount: 1, modifiedCount: 1, ... }   the old notes field is gone

In a sentence

  • “Calling replaceOne with only a new name wiped out the recipe's ingredients.”
  • “The editor saves the full recipe form with replaceOne, so a field the cook cleared really disappears.”

Level: Apprentice · More MongoDB terms at this level

Updated