Drop collection

In MongoDB, the db.collection.insert() method is used to add or insert new documents into a collection in your database.

Upsert

There are also two methods "db.collection.update()" method and "db.collection.save()" method used for the same purpose. These methods add new documents through an operation called upsert.

Upsert is an operation that performs either an update of existing document or an insert of new document if the document to modify does not exist.

Syntax

snippet
>db.COLLECTION_NAME.insert(document)

Let?s take an example to demonstrate how to insert a document into a collection. In this example we insert a document into a collection named rookienerd. This operation will automatically create a collection if the collection does not currently exist.

Example

snippet
db.rookienerd.insert(
   {
     course: "java",
     details: {
        duration: "6 months",
        Trainer: "Sonoo jaiswal"
     },
     Batch: [ { size: "Small", qty: 15 }, { size: "Medium", qty: 25 } ],
     category: "Programming language"
   }
)

After the successful insertion of the document, the operation will return a WriteResult object with its status.

Output:

Output
WriteResult({ "nInserted" : 1 })

Here the nInserted field specifies the number of documents inserted. If an error is occurred then the WriteResult will specify the error information.

Check the inserted documents

If the insertion is successful, you can view the inserted document by the following query.

snippet
>db.rookienerd.find()

You will get the inserted document in return.

Output:

Output
{ "_id" : ObjectId("56482d3e27e53d2dbc93cef8"), "course" : "java", "details" : { "duration" : "6 months", "Trainer" : "Sonoo jaiswal" }, "Batch" : [ {"size" : "Small", "qty" : 15 }, { "size" : "Medium", "qty" : 25 } ], "category" : "Programming language" }

Note: Here, the ObjectId value is generated by MongoDB itself. It may differ from the one shown.

MongoDB insert multiple documents

If you want to insert multiple documents in a collection, you have to pass an array of documents to the db.collection.insert() method.

Create an array of documents

Define a variable named Allcourses that hold an array of documents to insert.

snippet
var Allcourses =
    [
      {
        Course: "Java",
        details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
        Batch: [ { size: "Medium", qty: 25 } ],
        category: "Programming Language"
      },
      {
        Course: ".Net",
        details: { Duration: "6 months", Trainer: "Prashant Verma" },
        Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
        category: "Programming Language"
      },
      {
        Course: "Web Designing",
        details: { Duration: "3 months", Trainer: "Rashmi Desai" },
        Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
        category: "Programming Language"
      }
    ];

Inserts the documents

Pass this Allcourses array to the db.collection.insert() method to perform a bulk insert.

snippet
> db.rookienerd.insert( Allcourses );

After the successful insertion of the documents, this will return a BulkWriteResult object with the status.

Output
BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })

Note: Here the nInserted field specifies the number of documents inserted. In the case of any error during the operation, the BulkWriteResult will specify that error.

You can check the inserted documents by using the following query:

snippet
>db.rookienerd.find()

Insert multiple documents with Bulk

In its latest version of MongoDB (MongoDB 2.6) provides a Bulk() API that can be used to perform multiple write operations in bulk.

You should follow these steps to insert a group of documents into a MongoDB collection.

Initialize a bulk operation builder

First initialize a bulk operation builder for the collection rookienerd.

snippet
var bulk = db.rookienerd.initializeUnorderedBulkOp();

This operation returns an unorder operations builder which maintains a list of operations to perform .

Add insert operations to the bulk object

snippet
bulk.insert(
   {
     course: "java",
     details: {
        duration: "6 months",
        Trainer: "Sonoo jaiswal"
     },
     Batch: [ { size: "Small", qty: 15 }, { size: "Medium", qty: 25 } ],
     category: "Programming language"
   }
);

Execute the bulk operation

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

snippet
bulk.execute();

After the successful insertion of the documents, this method will return a BulkWriteResult object with its status.

Output
BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 1, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })

Here the nInserted field specifies the number of documents inserted. In the case of any error during the operation, the BulkWriteResult will specify that error.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +