Reputation: 539
I'm trying to increment a value in a mongoDB document.
Here is the document structure
I'm looking to increment knowCnt on the object with the matching username and respective cardId (1001 in this case) .
Here's my code so far. It returns success but the value isn't incremented in the DB.
var knowIncr = function(cnt) {
db.collection("testusers").updateOne( //collection.update depreciated!!!
{ $and: [
{ username: "user1" },
{ cardId: 1001 },
]},
{ $inc: { knowCnt: 1 } }, //increment by 1
{ new: true },
(err, data) => {
if (err) {
console.log(err);
}
console.log("knowIncr success", data);
}
);
};
knowIncr();
I also tried .updateOne({ username: "user1", cardId: 1001}, ... to no avail.
Thanks
Upvotes: 0
Views: 78
Reputation: 621
You have to specify the array name before accessing one of their objects, here's an example:
db.testUsers.updateOne({
"username": "user1",
"progress.cardId": 1001
}, {
$inc: {
"progress.$.knowCnt": 1
}
});
Here's more info about updating arrays and regarding using the $
sign: https://docs.mongodb.com/manual/reference/operator/update/positional/
Upvotes: 1