Reputation: 111
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
Upvotes: 4
Views: 6473
Reputation: 376
For those who want to increment and set both on update in nodejs with mongodb npm package.
I had a similar error when i tried to $set with $inc so this is how i solved it:
db.collection("example").updateOne({
"apiId": 1
},
{
$set: {
"updatedAt": ISODate()
},
$inc: {
"dataCount": 10
}
})
Upvotes: 1
Reputation: 39
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:{}}]
Upvotes: 0
Reputation: 11
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.
Upvotes: 1
Reputation: 757
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
}
})
Upvotes: 2