MongoDB update. Trying to set one field from a property of another

前端 未结 4 1683
误落风尘
误落风尘 2021-02-05 20:08

What I\'m trying to do is pretty straightforward, but I can\'t find out how to give one field the value of another.

I simply want to update one field with the character

4条回答
  •  心在旅途
    2021-02-05 20:45

    Try the following code:

    db.collection.find(your_querry).forEach(function(doc) {
      doc.field1 = doc.field2.length;
      db.collection.save(doc);
    });
    

    You can use your_querry to select only part of the original collection do perform an update. If you want to process an entire collection, use your_querry = {}.

    If you want all operations to be atomic, use update instead of save:

    db.collection.find( your_querry, { field2: 1 } ).forEach(function(doc) {
      db.collection.update({ _id: doc._id },{ $set: { field1: doc.field2.length } } );
    });
    

提交回复
热议问题