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

$push $pull $addToSet का उपयोग

Array operators array fields के अंदर items add, remove, और de-duplicate करते हैं।

In this page:

  1. $push $pull $addToSet
Syntax
javascript
{ $push: { array_field: value } }
{ $addToSet: { array_field: value } }
{ $pull: { array_field: value } }

$push $pull $addToSet

$push एक value append करता है, $addToSet सिर्फ तभी append करता है जब यह पहले से न हो, $pull matching elements remove करता है, और $pop पहला या आखिरी remove करता है। एक साथ कई values add करने के लिए $each इस्तेमाल करें। सब array पर in place operate करते हैं।

Note: $addToSet बिना पहले read किए arrays को duplicates से free रखता है।

उदाहरण: $push $pull $addToSet

bash
test> db.posts.insertOne({ _id: 1, title: "Hello", tags: ["intro"] })
{ acknowledged: true, insertedId: 1 }
test> db.posts.updateOne({ _id: 1 }, { $push: { tags: { $each: ["news", "mongo"] } } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.posts.updateOne({ _id: 1 }, { $addToSet: { tags: "intro" } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 0 }
test> db.posts.updateOne({ _id: 1 }, { $pull: { tags: "news" } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.posts.findOne()
{ _id: 1, title: 'Hello', tags: [ 'intro', 'mongo' ] }

⚠️ 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. एक array item add करने के लिए $set इस्तेमाल करना
  2. यह उम्मीद करना कि $push duplicates avoid करेगा
  3. कई values के लिए $each भूल जाना
चैप्टर सारांश
  • $push append करता है
  • $addToSet uniquely append करता है
  • $pull matches remove करता है
  • $each कई values add करता है
🔒

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.