Reputation: 184
I am trying to increment a value of an element here's my array object
"options": [
{
"key": "banana",
"votes": 0
},
{
"key": "apple",
"votes": 0
},
{
"key": "mango",
"votes": 0
},
{
"key": "grapes",
"votes": 0
}
]
im trying to increment the votes value of the selected
item
while also matching the id
of that data
db().collection('polls').update(
{ _id: id, "options.key": item },
{$set: { $inc: { "options.$.votes" : 1 } }})
But it didn't work... the db()
here is a function that returns the db.. im not getting any errors.
here is the full data
{
"_id": {
"$oid": "5aae26203ab1cc0f15e43dc6"
},
"author": "me",
"title": "fruits you love the most",
"options": [
{
"key": "banana",
"votes": 0
},
{
"key": "apple",
"votes": 0
},
{
"key": "mango",
"votes": 0
},
{
"key": "grapes",
"votes": 0
}
]
}
Upvotes: 2
Views: 182
Reputation: 30739
Remove $set
and try. It should work then. Also, the db
should be used without paranthesis like db
and not db()
:
db.collection('polls').update(
{ _id: id, "options.key": item },
{ $inc: { "options.$.votes" : 1 } }
)
If you are running this query directly in your mongodb shell then you need to specify _id: ObjectId(id)
in your query so your query will be:
var id = '5aaf66812b0e3813178a8a14'
db.collection('polls').update(
{ _id: ObjectId(id), "options.key": item },
{ $inc: { "options.$.votes" : 1 } }
)
Upvotes: 2
Reputation: 42
You are doing thing all correct but only one mistake is $inc should not be inside $set.
Following will fulfil your requirement.
db.collection.update( {"options.key": "banana" }, { $inc: { "options.$.votes" : 1 } } )
Upvotes: 0