Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What am I doing wrong with $set and $inc in update

Tags:

I am trying this at the mongodb console:

db.foobar.update(    { name: "Foobar" },   {      $set : { foo: { bar: 'bar' },      $inc: { 'foo.count': 1 }    }  }, true) 

It returns with "ok", but db.foobar.find(), returns an empty record set. I'm trying to upsert a document, so it looks like the:

name: Foobar foo: {   bar: 'bar'   count: 1 } 

If the doc doesn't exist then create one with a count of 1. Otherwise, just increase the count. Why isn't above working?

like image 824
Christian Fazzini Avatar asked May 27 '12 10:05

Christian Fazzini


People also ask

How to update increment in MongoDB?

In MongoDB, the $inc operator is used to increment the value of a field by a specified amount. The $inc operator adds as a new field when the specified field does not exist, and sets the field to the specified amount. The $inc accepts positive and negative value as an incremental amount.


1 Answers

It seems to me that your code is actually trying to set the $inc field of the document rather than using the $inc modifier on the foo.count field. This might be what you want:

db.foobar.update(     { name: "Foobar" },      {         $set: { 'foo.bar': 'bar' },          $inc: { 'foo.count': 1 }      }, true) 

Hope this helps.

like image 159
nicolagi Avatar answered Sep 18 '22 22:09

nicolagi