How to perform Mongo get from previous value, modify and update?

In first part of my logic initially I would expect txt.numberAffected to be 1

.then(txt => FutureTasks.upsert({userid: details.userid}, {$set: {count: txt.numberAffected}}))

in second part of logic which comes later I would like to take new found value of txt[0].count , say = 2
and then replace it back into count field so now it should be 3?

.then(txt => FutureTasks.update({userid: txt[0]._id}, {$set: {count: txt[0].count + how to get previous value set above?}}))

MongoDB provides findAndModify for this:

https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/

However, this is not exposed on Meteor’s minimongo, so you will need to wrap the underlying rawCollection object, either with Meteor.wrapAsync:

const raw = myCollection.rawCollection();
const findAndModify = Meteor.wrapAsync(raw.findAndModify, raw);
// then use as
findAndModify(query, sort, doc, options);

or as a Promise, which you will get automatically with Meteor 1.4:

myCollection.rawCollection().findAndModify(query, sort, doc, options); // returns a Promise

See here for parameters: http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#findAndModify

EDIT: I note from the above link that findAndModify is deprecated and that you shoud use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.

You can just use the $inc operator.

For more info, check the mongodb docs: https://docs.mongodb.com/manual/reference/operator/update/inc/#up._S_inc

Not if you want a guaranteed atomic read-and-update operation, including multi-server use.

Hi Henribeck

I may not always want to $inc because it is taking a previous value and modifying to a new numerical value, but rather I am trying to find existing value in Mongodb that corresponds to userid and add it to a new value which is unknown

Hi Rob

I rephrased my question here:

Is this going to be using a simply solution than having to use rawCollections?

Why in mongodb shell

db.future_tasks.find

returns

db.future_tasks.find( db.future_tasks.findAndModify( db.future_tasks.findOne(

but not db.future_tasks.findAndUpdate, db.future_tasks.findAndDelete and db.future_tasksfindAndReplace? findAndModify is deprecated but yet it is the only one available???

Difference between findOndandUpdate vs findOneandReplace ?

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

https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/