Is it possible to update MongoDB field using value of another field?

Technology CommunityCategory: MongoDBIs it possible to update MongoDB field using value of another field?
VietMX Staff asked 5 months ago
Problem

In SQL we will use:

UPDATE Person SET Name = FirstName + ' ' + LastName

Is it possible with MongoDB?

You cannot refer to the document itself in an update (yet). You’ll need to iterate through the documents and update each document using a function. So consider:

db.person.find().snapshot().forEach(
  function(elem) {
    db.person.update({
      _id: elem._id
    }, {
      $set: {
        name: elem.firstname + ' ' + elem.lastname
      }
    });
  }
);