mongodb

The official MongoDB Node.js driver provides both callback-based and Promise-based interaction with MongoDB, allowing applications to take full advantage of the new features in ES6. The 2.x series of the driver is powered by a brand new core driver and BSON library.

  • A brand new MongoDB driver for Node.js that keeps compatibility with the 1.4.x driver series, only breaking behavior where the 1.4.x branch had significant problems. The driver also includes support for the shared CRUD API specification and the Server Discovery and Monitoring Specification (SDAM).
  • The MongoDB Node.js core driver is the new underpinning for the driver and is meant for framework developers that do not need the helpers and abstractions available in the full driver. This driver is not meant for end users, as it offers none of the conveniences of the higher level APIs.

Given that you have created your own project using `npm init` we install the mongodb driver and it’s dependencies by executing the following `NPM` command.

npm install mongodb –save

This will download the MongoDB driver and add a dependency entry in your `package.json` file.

Insert Documents

The insertOne and insertMany methods exist on the Collection class and are used to insert documents into MongoDB.

const MongoClient = require(‘mongodb’).MongoClient;

const assert = require(‘assert’);

// Connection URL

const url = ‘mongodb://localhost:27017’;

// Database Name

const dbName = ‘myproject’;

// Create a new MongoClient

const client = new MongoClient(url);

// Use connect method to connect to the Server

client.connect(function(err, client) {

assert.equal(null, err);

console.log(“Connected correctly to server”);

const db = client.db(dbName);

// Insert a single document

db.collection(‘inserts’).insertOne({a:1}, function(err, r) {

assert.equal(null, err);

assert.equal(1, r.insertedCount);

// Insert multiple documents

db.collection(‘inserts’).insertMany([{a:2}, {a:3}], function(err, r) {

assert.equal(null, err);

assert.equal(2, r.insertedCount);

client.close();

});

});

});

The first insert inserts a single document into the inserts collection. Notice that there’s no need to explicitly create a new inserts collection, as the server will create it implicitly when the first document is inserted. The method db.createIndex is only necessary when creating non-standard collections, such as capped collections or where parameters other than the defaults are necessary.

The insertOne and insertMany methods also accept a second argument which can be an options object. This object can have the following fields:

Parameter Type Description
w {Number/String, > -1 || ‘majority’} the write concern for the operation where < 1 returns an acknowledgment of the write with not results {ok:1} and w >= 1 or w = ‘majority’ acknowledges the write with full write results.
wtimeout {Number, 0} set the timeout for waiting for write concern to finish (combines with w option).
j (Boolean, default:false) write waits for journal sync.
serializeFunctions (Boolean, default:false) serialize functions on an object to mongodb, by default the driver does not serialize any functions on the passed in documents.
forceServerObjectId (Boolean, default:false) Force server to assign _id values instead of driver.

Updating Documents

The updateOne and updateMany methods exist on the Collection class and are used to update and upsert documents.

 

const MongoClient = require(‘mongodb’).MongoClient;

const assert = require(‘assert’);

// Connection URL

const url = ‘mongodb://localhost:27017’;

// Database Name

const dbName = ‘myproject’;

// Create a new MongoClient

const client = new MongoClient(url);

// Use connect method to connect to the Server

client.connect(function(err, client) {

assert.equal(null, err);

console.log(“Connected correctly to server”);

const db = client.db(dbName);

const col = db.collection(‘updates’);

// Insert a single document

col.insertMany([{a:1}, {a:2}, {a:2}], function(err, r) {

assert.equal(null, err);

assert.equal(3, r.insertedCount);

// Update a single document

col.updateOne({a:1}, {$set: {b: 1}}, function(err, r) {

assert.equal(null, err);

assert.equal(1, r.matchedCount);

assert.equal(1, r.modifiedCount);

// Update multiple documents

col.updateMany({a:2}, {$set: {b: 1}}, function(err, r) {

assert.equal(null, err);

assert.equal(2, r.matchedCount);

assert.equal(2, r.modifiedCount);

// Upsert a single document

col.updateOne({a:3}, {$set: {b: 1}}, {

upsert: true

}, function(err, r) {

assert.equal(null, err);

assert.equal(0, r.matchedCount);

assert.equal(1, r.upsertedCount);

client.close();

});

});

});

});

});

The update method also accepts a third argument which can be an options object. This object can have the following fields:

Parameter Type Description
w {Number/String, > -1 || ‘majority’} the write concern for the operation where < 1 returns an acknowledgment of the write with not results {ok:1} and w >= 1 or w = ‘majority’ acknowledges the write with full write results.
wtimeout {Number, 0} set the timeout for waiting for write concern to finish (combines with w option).
j (Boolean, default:false) write waits for journal sync.
multi (Boolean, default:false) Update one/all documents with operation.
upsert (Boolean, default:false) Update operation is an upsert.

Just as for insert, the update method allows you to specify a per operation write concern using the w, wtimeout and fsync parameters.

Removing Documents

The deleteOne and deleteMany methods exist on the Collection class and are used to remove documents from MongoDB.

const MongoClient = require(‘mongodb’).MongoClient;

const assert = require(‘assert’);

// Connection URL

const url = ‘mongodb://localhost:27017’;

// Database Name

const dbName = ‘myproject’;

// Create a new MongoClient

const client = new MongoClient(url);

// Use connect method to connect to the Server

client.connect(function(err, client) {

assert.equal(null, err);

console.log(“Connected correctly to server”);

const db = client.db(dbName);

const col = db.collection(‘removes’);

// Insert a single document

col.insertMany([{a:1}, {a:2}, {a:2}], function(err, r) {

assert.equal(null, err);

assert.equal(3, r.insertedCount);

// Remove a single document

col.deleteOne({a:1}, function(err, r) {

assert.equal(null, err);

assert.equal(1, r.deletedCount);

// Update multiple documents

col.deleteMany({a:2}, function(err, r) {

assert.equal(null, err);

assert.equal(2, r.deletedCount);

client.close();

});

});

});

});

The deleteOne and deleteMany methods also accept a second argument which can be an options object. This object can have the following fields:

Parameter Type Description
w {Number/String, > -1 || ‘majority’} the write concern for the operation where < 1 returns an acknowledgment of the write with not results {ok:1} and w >= 1 or w = ‘majority’ acknowledges the write with full write results.
wtimeout {Number, 0} set the timeout for waiting for write concern to finish (combines with w option).
j (Boolean, default:false) write waits for journal sync.
single (Boolean, default:false) Removes the first document found.

 

Just as for updateOne/updateMany and insertOne/insertMany, the deleteOne/deleteMany method allows you to specify a per operation write concern using the w, wtimeout and fsync parameters.

findOneAndUpdate, findOneAndDelete, and findOneAndReplace

The three methods findOneAndUpdate, findOneAndDelete and findOneAndReplace are special commands which allow the user to update or upsert a document and have the modified or existing document returned. When using these methods, the operation takes a write lock for the duration of the operation in order to ensure the modification is atomic.

const MongoClient = require(‘mongodb’).MongoClient;

const assert = require(‘assert’);

// Connection URL

const url = ‘mongodb://localhost:27017’;

// Database Name

const dbName = ‘myproject’;

// Create a new MongoClient

const client = new MongoClient(url);

// Use connect method to connect to the Server

client.connect(function(err, client) {

assert.equal(null, err);

console.log(“Connected correctly to server”);

const db = client.db(dbName);

const col = db.collection(‘findAndModify’);

// Insert a single document

col.insert([{a:1}, {a:2}, {a:2}], function(err, r) {

assert.equal(null, err);

assert.equal(3, r.result.n);

// Modify and return the modified document

col.findOneAndUpdate({a:1}, {$set: {b: 1}}, {

returnOriginal: false

, sort: [[a,1]]

, upsert: true

}, function(err, r) {

assert.equal(null, err);

assert.equal(1, r.value.b);

// Remove and return a document

col.findOneAndDelete({a:2}, function(err, r) {

assert.equal(null, err);

assert.ok(r.value.b == null);

client.close();

});

});

});

});

The findOneAndUpdate method also accepts a third argument which can be an options object. This object can have the following fields:

Parameter Type Description
w {Number/String, > -1 || ‘majority’} the write concern for the operation where < 1 returns an acknowledgment of the write with not results {ok:1} and w >= 1 or w = ‘majority’ acknowledges the write with full write results.
wtimeout {Number, 0} set the timeout for waiting for write concern to finish (combines with w option).
j (Boolean, default:false) write waits for journal sync.
upsert (Boolean, default:false) Perform an upsert operation.
sort (Object, default:null) Sort for find operation.
projection (Object, default:null) Projection for returned result
returnOriginal (Boolean, default:true) Set to false if you want to return the modified object rather than the original. Ignored for remove.

 

The findOneAndDelete function is designed to help remove a document.

Get industry recognized certification – Contact us

Menu