3

I want to update in Mongo the 'order' field to all of my documents so they will be 1..2..3..4....34.

After running this, they all have "order": "34". What am I doing wrong?

var i = 1;
db.images.find().forEach(function() {
    db.images.update(
        {},
        { "$set": {"order": NumberInt(i)} },
        { multi: true }
    );
    i++;
})
Giorgio
  • 13,129
  • 12
  • 48
  • 75
Yafim Simanovsky
  • 531
  • 7
  • 26
  • Possible duplicate of [Update field with another field's value in the document](http://stackoverflow.com/questions/2606657/update-field-with-another-fields-value-in-the-document) – styvane Nov 01 '16 at 09:51

1 Answers1

6

multi : true means all documents matching the query will be updated. And your query is {}, which matches all the documents. So, basically you are updating the order of all the documents in every iteration.

Also, snapshot mode has to be enabled on the cursor to ensure that the same document isn't returned more than once.

You could try this:

var i = 1;
db.images.find().snapshot().forEach(function(image) {
    db.images.update(
        {"_id" : image._id},
        { "$set": {"order": NumberInt(i)} }
    );
    i++;
})

From a performance standpoint, it is better to use the bulk APIs. bulkwrite

4J41
  • 5,005
  • 1
  • 29
  • 41