Insert a document

suggest change

Insert a document called ‘myFirstDocument’ and set 2 properties, greetings and farewell

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

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

MongoClient.connect(url, function (err, db) {
  if (err) throw new Error(err);
  db.collection('myCollection').insertOne({ // Insert method 'insertOne'
    "myFirstDocument": {
      "greetings": "Hellu",
      "farewell": "Bye"
    }
  }, function (err, result) {
    if (err) throw new Error(err);
    console.log("Inserted a document into the myCollection collection!");
    db.close(); // Don't forget to close the connection when you are done
  });
});

Collection method insertOne()

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

Argument| Type |Description| —— | — |—— |collection | string | A string specifying the collectiondocument | object | The document to be inserted into the collectionoptions | object | (optional) Optional settings (default: null)callback| Function | Function to be called when the insert operation is done

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