Node.js – Insert Document(s) to MongoDB Collection

In this Node.js Tutorial, we shall learn to insert one or more documents to MongoDB Collection from Node.js Application, using insertOne() and insertMany() method respectively, with examples.

Following is a step by step guide with an example to insert documents to MongoDB Collection from Node.js Application.

  1. Start MongoDB Service. Run the following command to start MongoDB Service
  2. Get the base URL to MongoDB Service. A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell. While the Mongo Shell starts up, it echoes back the base url of MongoDB.
  3. Prepare the complete URL. Append the Database name you want to connect to (say newdb), to the base URL.
  4. Create a MongoClient.
  5. Make connection from MongoClient to the MongoDB Server with the help of URL. Once the MongoClient is done trying to make a connection, the callback function receives error and db object as arguments.

    If the connection is successful, the db object points to the database, newdb.

  6. Insert documents to specified MongoDB Collection. Following is the syntax of insertOne() and insertMay() methods used to insert documents to collection in MongoDB from Node.js. insertOne()


    <collection_name>Name of the new MongoDB Collection, that we would like to create
    <document>Single document that has to be inserted to MongoDB Collection
    <document_array>Array of documents to be inserted to MongoDB Collection
    <callback_function>This Node.js Callback Function is called after Node has tried creating a collection, and ready with the result. The callback function receives error and result object as arguments.

insertOne() – Example Node.js program

insertMany() – Example Node.js program

The first entry was from first example, and the rest three have been inserted with this example.


MongoDB Tutorial – Learn MongoDB from basics with Examples.

Conclusion :

In this Node.js MongoDB tutorial : Node.js – Insert Document(s) to MongoDB Collection, we have learnt to insert one or more documents to MongoDB Collection using insertOne() and insertMany() methods, from Node.js Application using mongodb package. In our next tutorial – Node.js MongoDB Find, we shall learn to query documents from MongoDB Collection.