Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top