3

I need to update a field using some expression. Given a DBObject query, how can I multiply or divide given field by an argument value?

How can I write a function performing operation something like this, but in Java:

function(DBObject queryObject, String fieldToUpdate, Double argumentValue) { 
    collection.find(queryObject).forEach(function(e) {
        // update field given by input argument "fieldToUpdate", something like..
        // e.put(fieldToUpdate, e.get(fieldToUpdate)/argumentValue); ??
        collection.save(e);
    });
}

Is it possible using "$set" and find() or findAndModify()? If yes, how can update existing value using an expression like existingValue / argumentValue?

1 Answer 1

1

At the moment, MongoDB doesn't allow you to update the value of a field according to an existing value of a field. Which means, you can't do the following SQL:

UPDATE foo SET field1 = field1 / 2;

In MongoDB, you will need to do this in your application, but be aware that this is no longer an atomic operation as you need to read and then write.

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

Comments

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.