MongoError: The dollar ($) prefixed field '$cond' in 'energy.$cond' is not valid for storage

When i try to run this code below i get the error: MongoError: The dollar ($) prefixed field ‘$cond’ in ‘energy.$cond’ is not valid for storage. How can i fix this issue?

var updateDoc = {

        $set: { 

            energy: { 

                $cond: { 

                    if: { $gt: [ { $add: [ "$energy", 20 ] }, 100 ] }, 

                    then: 100, 

                    else: { $add: [ "$energy", 20 ] } 

                } 

            } 

        }

      }

Hello @JasoO,

$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

1 Like

Yeah i figured it out just now, thank you anyway :slight_smile:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.