How to MongoDB- Insert Documents into collection

In this guide, we are going to discuss how to insert documents into a collection. MongoDB stores documents in Bson form. Documents in MangoDB are analogous to the records of an RDBMS. Insert, update, and delete documents operations can be performed on a collection.

Document Oriented Database

MongoDB insert documents


The db.collection.insert() method is used to add or insert new documents into a collection in your database.




       course: "MongoDB",  
       category: "Database",
       by: 'lauyou',


     WriteResult({ "nInserted" : 1 })


You can view the inserted document by the following query.



     { "_id" : ObjectId("56482d3e27e53d2dbc93cef8"), "course" : "MongoDB", 
     "category" : "Database", "by"  :  "lauyou" }


To insert multiple documents in a single query, you can pass an array of documents in insert() command. Also you can insert multiple arrays.

           course: 'MySQL', 
           catagory: 'Database',
           by: ''
           course: 'Java', 
           catagory: 'Programming',
           by: '',


        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]

You can use also to add documents.


Insert document from file

The mongoimport tool imports content from an Extended JSON, CSV, or TSV export created by mongoexport

If MongoDB is installed in the C:\MongoDB folder, and the file to be imported is located at C:\Data.json, the format of the mongoimport command is:

Insert document from file
     C:\>mongodb\bin\mongoimport –host localhost:27017 –db db –collection docs < 

In this example, “db” is the name of the database and “docs” is the name of the collection into which the data will be inserted.  The database and collection will be created if they do not already exist.

Muhsin Yakkiparamban

Muhsin Yakkiparamban is the co-founder of Lauyou Learning. Muhsin holds Bachelor Degree in Civil Engineering from KMCT Calicut.

You may also like...