StackOverflowed
StackOverflowed

Reputation: 5975

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: [] }

Upvotes: 8

Views: 4053

Answers (2)

Ricardo Araque
Ricardo Araque

Reputation: 81

If you can´t find the findAndModify method to use on your collection,you can use the findOneAndUpdate method.

Here is how to use:

The following code finds the first document where name : R. Stiles and increments the score by 5:

const result = await db.grades.findOneAndUpdate(
   { "name" : "R. Stiles" }, //also you can search for id
   { $inc: { "points" : 5 } }
)

The code returns the original document before the update inside the "value" propety:

{ _id: 6319, name: "R. Stiles", "points" : 0,... } // result.value returns document before update, but in the db it changued

If you want get the document uploaded, you has to set "returnNewDocument" to true, so the operation would return the updated document instead.

I hope it works for you.

source: https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate/

Upvotes: 2

Abdullah Rasheed
Abdullah Rasheed

Reputation: 3752

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,
)

Upvotes: 12

Related Questions