Eliranf
Eliranf

Reputation: 43

MongoDB update and increment operation, when update data is an empty hash

When using Ruby-on-Rails with ruby version 2.2.0, MongoDB version 3.0.5,

I am experiencing a weird behaviour when trying to execute an update query contains both update and increment, when the update data is an empty hash:

When running the command:

(1) db.collection.update({'user_id' => 123456}, {'$set' => {}, '$inc' => { 'counter' => 1 }}, {:upsert => true})

The value of the field counter left as it was (no change).

When running the command:

(2) db.collection.update({'user_id' => 123456}, {'$inc' => { 'counter' => 1 }}, {:upsert => true})

The value of the field counter is incremented by 1, as expected.

Can someone please explain to me why command (1) has a different result than command (2)?

Upvotes: 0

Views: 252

Answers (1)

Louis F.
Louis F.

Reputation: 2048

db.collection.update({'user_id' => 123456}, {'$set' => {}, '$inc' => { 'counter' => 1 }}, {:upsert => true})

outputs '$set' is empty. You must specify a field like so: {$mod: {<field>: ...}} exception

This might be the reason why your counter is not incremented.

Which version of mongodb are you using Mine is 2.6

Upvotes: 1

Related Questions