Update MongoDB field using value of another field

Technology CommunityCategory: MongoDBUpdate MongoDB field using value of another field
VietMX Staff asked 3 years ago

Consider SQL command:

UPDATE Person SET Name = FirstName + ' ' + LastName

In Mongo, is it possible to update the value of a field using the value from another field?

Answer

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 like:

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