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++;
})
1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks 4J41, this worked. I guess I wasn't so sure until now about how {"_id" : image._id} would help. Cheers.
Styvane can you explain what you're referring to?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.