'Unhandled rejection MongoError: The dollar ($) prefixed field '$inc' in '$inc' is not valid for storage

I am getting following error while i am trying to increment a field by a specified value in mongodb using $inc

"Unhandled rejection MongoError: The dollar ($) prefixed field '$inc' in '$inc' is not valid for storage."

Below is my code

APILog.update({ apiId: 1 }, {$inc:{"dataCount":10}}); 

Thanks in advance



Solution 1:[1]

You should include values as JSON in Mongo Query. Might be due to this you are facing an issue. Can you please try by updating your query as:

APILog.update({
  "apiId": 1
},
{
  "$inc": {
    "dataCount": 10
  }
})

Solution 2:[2]

I ran into same exception and was able to solve this way. Following is the syntax of executing a general command in mongodb, updated with your example data:

db.runCommand(
    update: "<replace-with-collection-name>",
    updates: [
        {
            q:{"apiId": 1}, u: {"$inc": {"dataCount": 10}}
        }
    ]
)

Escape the $ character as per rules of node.js, if needed.

Solution 3:[3]

Since I came across this... I've found at least for me that it works to use brackets if you're doing an aggregation inside your update. Like so:

db.example.updateMany(
    {FirstRecord:{$in:recordids}},
    [{$set:{
        RecordCode:{
            $first:{
                $map:{
                    ...
                }
            }
        }
     }}]
 )

In my case I'm trying to update a field which is a code we will use later to match to other documents, and have a list of ObjectIds for the target records and a dictionary from ID to code. Anyway I found I received a similar error until I added the brackets around [{$set:{}}]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mayuri S Kulkarni
Solution 2
Solution 3 user50511