Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update increment two fields in one command in MongoDB?

Tags:

mongodb

The documentation tells me this is legal if I want to set one value and increment another:

{ $set : { x : 1 }, $inc : { y : 1 } }

What if I want increment both variables? I'm trying this but it isn't working:

{ $inc : [{ y : 1 }, { x : 1 }] }

Is this possible?

like image 271
Zach Avatar asked Aug 19 '11 21:08

Zach


People also ask

How do I increment a field in MongoDB?

The $inc operator increments a field by a specified value and has the following form: { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

Can we update _ID in MongoDB?

The _id field is immutable—that is, once a document exists in your MongoDB system, it has, by definition, been assigned an _id, and you cannot change or update its primary key. That said, _id can be overridden when you insert new documents, but by default it will be populated with an ObjectID.

What is Upsert in MongoDB?

In MongoDB, upsert is an option that is used for update operation e.g. update(), findAndModify(), etc. Or in other words, upsert is a combination of update and insert (update + insert = upsert).


1 Answers

I'm an idiot:

{ $inc : { y : 1, x : 1 } }

like image 116
Zach Avatar answered Sep 30 '22 22:09

Zach