Search code examples
mongodbmonk

Using the value of a MongoDB field to update another field


I have a MongoDB document with a structure like this:

{
    testValue: 10,
    maxValue: 20
}

I want to set testValue to an arbitrary integer value between 0 and maxValue. Ideally, I would do something like this:

db.collection.update(
    {},
    {
        $set: { 'testValue': newValue },
        $min: { 'testValue': 0 },
        $max: { 'textValue': $maxValue }
    }
)

But that obviously doesn't work. There are a handful of threads that relate to this question (e.g. Update MongoDB field using value of another field), but they're all a few years old, and I can't find pertinent information in the official documentation. Is there a way to do what I want, or do I have to use find() to get maxValue then do a separate call to the database using update()?


Solution

  • This is still not possible in Mongo 3.2 or lower, check for example these JIRA tickets:

    1. Self referential updates
    2. Allow update to compute expressions using referenced fields