Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Mongo, Increment and return value -- possible in 1 call?

In Mongo, is it possible to increase and get the result of the increment?

collection.update({id: doc_id}, {$inc: {view_count: 1}});

I tried to output the result of that statement (in node) and I got the following:

 { _id: 1,
  _state: undefined,
  _result: undefined,
  _subscribers: [] }
like image 208
StackOverflowed Avatar asked Oct 30 '15 16:10

StackOverflowed


People also ask

How do I 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.

What is multi in MongoDB?

To update multiple documents in a collection, set the multi option to true. db.collection.update( query, update, { upsert: boolean, multi: boolean, writeConcern: document } ) multi is optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

How do I decrement a number value in mongoose?

To increment a number field value in Mongoose, you can use the $inc operator. This operator increments a field by a specified value.


1 Answers

You can use findAndModify. Add the new:true option.

According to the docs:

The findAndModify command modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.

You could do the following:

db.collection.findAndModify(
    query:  {_id: doc_id},
    update: { $inc: { view_count :1 } },
    new: true,
)
like image 118
Abdullah Rasheed Avatar answered Nov 07 '22 17:11

Abdullah Rasheed