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: [] }
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.
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.
To increment a number field value in Mongoose, you can use the $inc operator. This operator increments a field by a specified value.
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,
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With