Insert a document

suggest change

Insert one document into myCollection with the properties greetings and farewell. Since driver 3.x, MongoClient.connect passes a client, and the database name is selected with client.db(). Driver 4 and later drop the callback and return a promise.

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017';

MongoClient.connect(url, function (err, client) {
  if (err) throw err;
  var db = client.db('test');
  db.collection('myCollection').insertOne({
    greetings: 'Hellu',
    farewell: 'Bye'
  }, function (err, result) {
    if (err) throw err;
    console.log('Inserted a document into the myCollection collection!');
    client.close();
  });
});

Collection method insertOne()

db.collection(collection).insertOne(document, options, callback)

Argument Type Description
collection string Name of the collection
document object The document to insert
options object Optional settings. The default is null.
callback function Called when the insert finishes. Removed in driver 4.

The callback function takes two arguments

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents