← Back to MongoDB Course | Chapter 4: CRUD — Update | Lesson 5 of 7

replaceOne() का उपयोग

replaceOne एक पूरे document को एक नए से swap करता है, सिर्फ _id रखते हुए।

In this page:

  1. replaceOne()
Syntax
javascript
db.collection_name.replaceOne(filter, { field1: value1, field2: value2 })

replaceOne()

updateOne के उलट, replaceOne बिना operators के एक full replacement document लेता है। नए document में न होने वाली हर field गायब हो जाती है। यह तब useful है जब आपको एक exact नई shape चाहिए लेकिन dangerous है अगर आपका मतलब एक partial change से था।

Note: replaceOne सिर्फ तभी इस्तेमाल करें जब आपका इरादा _id को छोड़कर सब कुछ overwrite करने का हो।

उदाहरण: replaceOne()

bash
test> db.users.insertOne({ _id: 1, name: "Ada", age: 36, city: "London" })
{ acknowledged: true, insertedId: 1 }
test> db.users.replaceOne({ _id: 1 }, { name: "Ada Lovelace", role: "mathematician" })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.users.findOne()
{ _id: 1, name: 'Ada Lovelace', role: 'mathematician' }

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक छोटे change के लिए replaceOne इस्तेमाल करना
  2. replacement में operators शामिल करना
  3. _id बदलने की कोशिश करना
चैप्टर सारांश
  • replaceOne पूरा document overwrite करता है
  • _id रखा जाता है
  • कोई update operators allowed नहीं
  • Partial changes के लिए updateOne इस्तेमाल करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.