2

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
 }
 ]
}
asked Mar 19, 2018 at 8:52
0

2 Answers 2

2

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 } }
)
answered Mar 19, 2018 at 8:55
Sign up to request clarification or add additional context in comments.

2 Comments

Are you running this script from mongoose or directly on mongodb?
If its directly on mongodb then you should be using _id: ObjectId(id)
0

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 } }
 )
answered Mar 19, 2018 at 9:02

2 Comments

this works but i also want to match the data id so it just updates that particular data..
then you can add data id field too in search filter. :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.