Three ways MongoDB inserts data

  • 2020-05-09 19:34:07
  • OfStack


insert () method:
      the following is a document with 1 and 3 fields inserted into the inventory collection:
             

db.inventory.insert( { _id: 10, type: "misc", item: "card", qty: 15 } )

              in the real example, the document has a user-specified _id field with a value of 10, which must be uniquely 1 in the inventory collection.
update () method:
      calls the update() method to create a new document using the upsert flag when no document matches the query criteria. The following example creates a new document when the inventory collection does not contain documents {type:"books",item:"journal"} :

           

 db.inventory.update(
                         { type: "book", item : "journal" },
                         { $set :     { qty: 10 } },
                         { upsert :true     }
                ) 


  MongoDB adds the _id field and assigns a 1-only ObjectId as its value. The new document contains information from the query < query > Conditions for the item and type fields, and from the update < update > Parameter qty field:
           
 { "_id" : ObjectId("51e8636953dbe31d5f34a38a"), "item" : "journal", "qty" : 10, "type" : "book" }

save () method:
      inserts a document using the save() method, which saves a document that does not contain the _id field or that contains the _id field but does not have the value of that field in the collection. The following example creates a new document in the inventory collection:
             
db.inventory.save( { type: "book", item: "notebook", qty: 40 } )

      MongoDB adds the _id field and assigns a 1-only ObjectId as its value.
             
{ "_id" : ObjectId("51e866e48737f72b32ae4fbc"), "type" : "book", "item" : "notebook", "qty" : 40 } 

 


Related articles: