MongoDB: Updating documents using data from the same document [duplicate]

Update: If all you have to do is change the structure of a document without changing the values, see gipset’s answer for a nice solution.


According to a (now unavailable) comment on the Update documentation page, you cannot reference the current document’s properties from within an update().

You’ll have to iterate through all the documents and update them like this:

db.events.find().snapshot().forEach(
  function (e) {
    // update document, using its own properties
    e.coords = { lat: e.lat, lon: e.lon };

    // remove old properties
    delete e.lat;
    delete e.lon;

    // save the updated document
    db.events.save(e);
  }
)

Such a function can also be used in a map-reduce job or a server-side db.eval() job, depending on your needs.

Leave a Comment