I have a document that looks similar to this:
{
'user_id':'{1231mjnD-32JIjn-3213}',
'name':'John',
'campaigns':
[
{
'campaign_id':3221,
'start_date':'12-01-2012',
'worker_id': '00000'
},
{
'campaign_id':3222,
'start_date':'13-01-2012',
'worker_id': '00000'
},
...
etc
...
]
}
Say I want to increment the campaign_id of element 7 in the campaigns array.
Using the dot with the mongoose driver, I thought I could do this:
camps.findOneAndUpdate({name: "John"}, {$inc: {"campaigns.7.campaign_id": 1}}, upsert: true, function(err, camp) {...etc...});
This doesn't increment the campaign_id.
Any suggestions on incrementing this?
asked Dec 22, 2012 at 1:27
user1460015
2,0033 gold badges29 silver badges37 bronze badges
1 Answer 1
You've got the right idea, but your upsert option isn't formatted correctly.
Try this:
camps.findOneAndUpdate(
{name: "John"},
{$inc: {"campaigns.7.campaign_id": 1}},
{upsert: true},
function(err, camp) {...etc...});
answered Dec 22, 2012 at 2:13
JohnnyHK
313k70 gold badges632 silver badges479 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
user1460015
For some reason I do not understand, if I say:
var update = 'campaigns.' + position + ".campaign_id" and then $inc: {update: 1} does not work (where position is an integer). But works fine if I spell it out like above: $inc: {"campaigns.7.campaign_id": 1}. Do you know why?JohnnyHK
Because you can't use a variable as a key name in a JavaScript immediate object. So you have to build up your update object programmatically.
var update = {$inc: {}}; update.$inc['campaigns.' + position + ".campaign_id"] = 1;user1460015
ahh... interesting. Thanks!
lang-js