MongoDB Insert Records In Collection | MongoDB Insert Example

📔 : MongoDB 🔗

पिछले topic में आपने Collection (Table) create करना सीखा , इस topic में हम collection में records / document को insert करना सीखेंगे।

जैसे SQL databases table में stored records को row(s) कहते हैं बैसे ही के MongoDB Collection में stored records को Document(s) कहते हैं। और इस topic में हम सीखेंगे कि किसी collection में new document को कैसे insert करते हैं।

Insert document in MongoDB in Hindi

MongoDB के किसी collection में new document insert करने के लिए collection को dot . operator के साथ insert() function का use किया जाता है , जिसमे document object pass करते हैं।

Syntax

db.collection_name.insert(object)

MongoDB Insert Example

पिछले topic में हमने एक users name का collection बनाया था , उसी collection में यह कुछ documents insert करने का example देखेंगे।

Switch database -

use mydatabase

Insert document

db.users.insert({
  "name" : "Pyare Lal",
  "prefession" : "Software developer",
  "location" : "UP , India",
  "salery" : 10000,
  "age" : 32
})

MongoDB में document insert करते time अगर collections exist होगा तो record insert हो जायगा नहीं तो new collection create होकर record insert होगा।

इसके अलावा primary id के लिए document में _Id automatically field add हो जायगा तो , आपको manually primary id define करने की जरूरत नहीं।

MongoDB insertMany() Example

insertMany() function का use करके आप एक साथ एक से ज्यादा documents को एक साथ insert कर सकते हैं। इसमें आपको document के Objects का Array pass करना पड़ेगा।

db.users.insertMany([
  {
    "name" : "Ramu Kaka",
    "location" : "Ragargh", 
    "age" : 54
  },
  {
    "name" : "Gabbar",
    "location" : "Ragargh", 
    "age" : 54
  },
  {
    "name" : "Raju",
    "location" : "India", 
    "age" : 33
  }
])

Output

{
  "acknowledged" : true,
  "insertedIds" : [ 
      ObjectId("64f5575e4984b45231af1b03"), 
      ObjectId("64f5575e4984b45231af1b04"), 
      ObjectId("64f5575e4984b45231af1b05")
  ]
}

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers