Insert Data with Node.js

Overview

You can use the insertOne method and the insertMany method to add documents to a collection in MongoDB. If you attempt to add documents to a collection that does not exist, MongoDB will create the collection for you.

Prerequisites

In the node shell, define the following variables to access the required modules as well as to initialize url to the MongoDB uri.

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/test';

Insert a Document

Insert a document into a collection named restaurants. The operation will create the collection if the collection does not currently exist.

Defines a function insertDocument:

var insertDocument = function(db, callback) {
   db.collection('restaurants').insertOne( {
      "address" : {
         "street" : "2 Avenue",
         "zipcode" : "10075",
         "building" : "1480",
         "coord" : [ -73.9557413, 40.7720266 ]
      },
      "borough" : "Manhattan",
      "cuisine" : "Italian",
      "grades" : [
         {
            "date" : new Date("2014-10-01T00:00:00Z"),
            "grade" : "A",
            "score" : 11
         },
         {
            "date" : new Date("2014-01-16T00:00:00Z"),
            "grade" : "B",
            "score" : 17
         }
      ],
      "name" : "Vella",
      "restaurant_id" : "41704620"
   }, function(err, result) {
    assert.equal(err, null);
    console.log("Inserted a document into the restaurants collection.");
    callback();
  });
};

Call the insertDocument function.

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  insertDocument(db, function() {
      db.close();
  });
});

A successful insert should print out the following line:

Inserted a document into the restaurants collection.

With a successful insert, the result object includes an insertedId property that contains the _id of the inserted document.

If the document passed to the insertOne method does not contain the _id field, the driver automatically adds the field to the document and sets the field’s value to a generated ObjectId.

Additional Information

In the Node.js documentation, see insertOne, insertMany and Documents.

In the MongoDB Manual, see also the Insert Documents tutorial.