Update Data with Node.js

Overview

You can use the updateOne method, updateMany method, and replaceOne method to update documents of a collection. The methods accept the following parameters:

  • a filter document to match the documents to update,
  • an update document to specify the modification to perform, and
  • an options parameter (optional).

To specify the filter, use the same structure and syntax as the query conditions. See Find or Query Data with Node.js for an introduction to query conditions.

You cannot update the _id field.

Prerequisites

The examples in this section use the restaurants collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset.

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';

Update Specific Fields

To change a field value, MongoDB provides update operators, such as $set to modify values. Some update operators, such as $set, will create the field if the field does not exist. See the individual update operators reference.

Update Top-Level Fields

The following operation updates the first document with name equal to "Juni", using the $set operator to update the cuisine field and the $currentDate operator to update the lastModified field with the current date.

Define an updateRestaurants function as follows:

var updateRestaurants = function(db, callback) {
   db.collection('restaurants').updateOne(
      { "name" : "Juni" },
      {
        $set: { "cuisine": "American (New)" },
        $currentDate: { "lastModified": true }
      }, function(err, results) {
      console.log(results);
      callback();
   });
};

Call the updateRestaurants function.

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

  updateRestaurants(db, function() {
      db.close();
  });
});

The updateOne returns the number of documents updated.

Update an Embedded Field

To update a field within an embedded document, use the dot notation. When using the dot notation, enclose the whole dotted field name in quotes. The following updates the street field in the embedded address document.

Define an updateRestaurants function as follows:

var updateRestaurants = function(db, callback) {
   db.collection('restaurants').updateOne(
      { "restaurant_id" : "41156888" },
      { $set: { "address.street": "East 31st Street" } },
      function(err, results) {
        console.log(results);
        callback();
   });
};

Call the updateRestaurants function.

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

  updateRestaurants(db, function() {
      db.close();
  });
});

The updateOne returns the number of documents updated.

Update Multiple Documents

To update multiple documents, use the updateMany method. The following operation updates all documents that have address.zipcode field equal to "10016" and cuisine field equal to "Other", setting the cuisine field to "Category To Be Determined" and the lastModified field to the current date.

Define an updateRestaurants function as follows:

var updateRestaurants = function(db, callback) {
   db.collection('restaurants').updateMany(
      { "address.zipcode": "10016", cuisine: "Other" },
      {
        $set: { cuisine: "Category To Be Determined" },
        $currentDate: { "lastModified": true }
      }
      ,
      function(err, results) {
        console.log(results);
        callback();
   });
};

Call the updateRestaurants function.

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

  updateRestaurants(db, function() {
      db.close();
  });
});

The updateMany returns the number of documents updated.

Replace a Document

To replace the entire document except for the _id field, pass an entirely new document as the second argument to the replaceOne method. The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable. If you do include the _id field, it must be the same value as the existing value.

Important

After the update, the document only contains the field or fields in the replacement document.

After the following update, the modified document will only contain the _id field, name field, the address field. i.e. the document will not contain the restaurant_id, cuisine, grades, and the borough fields.

Define an updateRestaurants function as follows:

var updateRestaurants = function(db, callback) {
   db.collection('restaurants').replaceOne(
      { "restaurant_id" : "41704620" },
      {
        "name" : "Vella 2",
        "address" : {
           "coord" : [ -73.9557413, 40.7720266 ],
           "building" : "1480",
           "street" : "2 Avenue",
           "zipcode" : "10075"
        }
      },
      function(err, results) {
        console.log(results);
        callback();
   });
};

Call the updateRestaurants function.

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

  updateRestaurants(db, function() {
      db.close();
  });
});

The replaceOne returns the number of documents updated.

Additional Information

If no document matches the update condition, the default behavior of the update method is to do nothing. By specifying the upsert option to true, the update operation either updates matching document(s) or inserts a new document if no matching document exists. In the Node.js documentation, see updateOne, updateMany, and replaceOne.

In MongoDB, write operations are atomic on the level of a single document. If a single update operation modifies multiple documents of a collection, the operation can interleave with other write operations on that collection. In the MongoDB Manual, see Atomicity.

For all available update operators, see the Update Operators reference page in the MongoDB Manual.