How can i fix this mongodb error?: MongoError: The dollar ($) prefixed field '$cond' in 'energy.$cond' is not valid for storage

Viewed 182

I get this error when i try to use the following code for mongoDB:

var updateDoc = {
    $set: { 
        energy: { 
            $cond: { 
                if: { $gt: [ { $add: [ "$energy", 20 ] }, 100 ] }, 
                then: 100, 
                else: { $add: [ "$energy", 20 ] } 
            } 
        } 
    }
  }

How can i fix this problem?

1 Answers

$cond is a aggregation operator, update can't allow that operator in this simple query,

Look at the update with aggregation pipeline starting from MongoDB v4.2,

You just need to wrap updateDoc object in to array,

var updateDoc = [
  {
    $set: {
      energy: {
        $cond: {
          if: { $gt: [{ $add: ["$energy", 20] }, 100] },
          then: 100,
          else: { $add: ["$energy", 20] }
        }
      }
    }
  }
]

Playground

Related