MongoDB insert documents

In MongoDB, the db.collection.insert() system is utilized to include or embed new reports into a gathering in your database.

There are additionally two techniques "db.collection.update()" strategy and "" system utilized for the same reason. These techniques include new reports through an operation called upsert.

Upsert is an operation that performs either an overhaul of existing report or an addition of new archive if the record to adjust does not exist.



Let's take an illustration to exhibit how to embed an archive into an accumulation. In this sample we embed a report into an accumulation named javatportal. This operation will consequently make an accumulation if the gathering does not as of now exist.

     item: "ABC1",
     details: {
        model: "14Q3",
        manufacturer: "XYZ Company"
     stock: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ],
     category: "clothing"

The operation returns a WriteResult object with the status of the operation. A successful insert of the document returns the following object:

WriteResult({ "nInserted" : 1 })

Check the inserted documents

On the off chance that the insertion is fruitful, you can see the embedded record by the accompanying question.


MongoDB insert multiple documents

The following case performs a mass supplement of three reports by passing a variety of records to the addition() technique. As a matter of course, MongoDB performs a requested addition. With requested additions, if a mistake happens amid a supplement of one of the archives, MongoDB returns on blunder without preparing the remaining records in the cluster.

     { _id: 11, item: "pencil", qty: 50, type: "no.2" },
     { item: "pen", qty: 20 },
     { item: "eraser", qty: 25 }

The operation inserted the following three documents:

{ "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" } { "_id" : ObjectId("51e0373c6f35bd826f47e9a0"), "item" : "pen", "qty" : 20 } { "_id" : ObjectId("51e0373c6f35bd826f47e9a1"), "item" : "eraser", "qty" : 25 }

Insert Multiple Documents with Bulk

MongoDB gives a Bulk() API that you can use to perform different compose operations in mass. The accompanying succession of operations portrays how you would utilize the Bulk() API to embed a gathering of reports into a MongoDB accumulation.

var bulk = db.inventory.initializeUnorderedBulkOp();

Add insert operations to the bulk object.

Add two insert operations to the bulk object using the Bulk.insert() method.

     item: "BE10",
     details: { model: "14Q2", manufacturer: "XYZ Company" },
     stock: [ { size: "L", qty: 5 } ],
     category: "clothing"
     item: "ZYT1",
     details: { model: "14Q1", manufacturer: "ABC Company"  },
     stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 } ],
     category: "houseware"

Execute the bulk operation.

Call the execute() method on the bulk object to execute the operations in its list.


Upcoming latest Additional Examples and Methods