MongoError: Invalid $set :: Caused by :: FieldPath field names may not start with "$"

Hello everyone, for some reason i get this error when i try to run this:

[{
      $set: { 
      health: { 
          $cond: { 
              if: { $gt: [ { $add: [ "$health", 20 ] }, 150 ] }, 
              then: 150, 
              else: { $add: [ "$health", 20 ] } 
          } 
      },
      $inc: {
        bandageamount: -1,
        },
        $pull: {
        items: ["Bandage"]
        }, 
  }
}
]

Could anyone help me with this?

Your $set is not terminated correctly so your following $inc is actually part of the $set object rather than being another object. Since top level field cannot start with $ then you get the given error.

What would be the way to fix that?

It would be to terminate $set at the right place, just before the $inc. You do that by moving the last closing brace } just before the comma that is supposed to separate the $set object from the $inc object.

1 Like

The issue here is that you are mixing two different syntax types here.

Update takes either regular modifiers ($inc is one of those) or aggregation syntax, if you are using pipeline syntax, which you are ([]).

So your $set for field health is fine, but you are not allowed to mix in $inc operator nor $pull. What you want is to express the whole thing as an aggregation:

[{$set: { 
    health: { 
       $cond: { 
          if: { $gt: [ { $add: [ "$health", 20 ] }, 150 ] }, 
          then: 150, 
          else: { $add: [ "$health", 20 ] } 
       } 
    },
    bandageamount: {$sum:["$bandageamount", -1]},
    items: {$filter:{
       input:"$items",
       cond:{$ne:["$$this","Bandage"]}
    }}
}} ]
1 Like

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