41543

conditional update in mongodb

Question:

I have the following schema below and need do an update which is detailed below. Not sure how to go about it.

UserPromo = new Schema sendFBInvite: earnedIntros: type: Number default: 0 earningActionCounter: type: Number default: 0 actions: type: Number default:1 earnings: earnedIntros: type: Number default: 0 usedIntros: type: Number default: 0

everytime sendFBInvite.earningActionCounter goes to 5 I want sendFBInvite.earnedIntros to increment and earnings.earnedIntros to increment by 1. At the same time I want to reset sendFBInvite.earningActionCounter to 0

Is there a way to do this in one call? thanks in advance for your help!

Answer1:

NO. The core of MongoDB is to have all the business logic in the application level and not DB. So in short I don't think its possible.

Side note: MongoDB is very fast and you can run multiple select/ find queries and then fire and update. Plus there is also findAndModify command (<a href="http://docs.mongodb.org/manual/reference/command/findAndModify/" rel="nofollow">http://docs.mongodb.org/manual/reference/command/findAndModify/</a>) by which might be good for you to look into.

Answer2:

this is old, but for others getting here... the earlier answer mentioned needing to do this in the application layer, which is correct. here's a pseudo-code example of how you might safely and efficiently perform such an update:

incrementActionCounter() { do { var tryagain = false // do the common action first, but only if it would not reach // the boundary condition (5) err = collection("").update( {"sendFBInvite.earnedActionCounter": {$ne: 4}}, {$inc:{"sendFBInvite.earnedActionCounter": 1}} ) // 'not found' means that it's likely already at 4... so... if err == "not found" { // still need a condition here, in case someone else updated // the value behind our back err = collection("").update({"sendFBInvite.earnedActionCounter": 4}, { $inc: { "sendFBInvite.earnedIntros":1, "earnings.earnedIntros":1 }, $set:{ "sendFBInvite.earnedActionCounter": 0 } }) // 'not found' here means something changed between our 2 queries if err == "not found" { tryagain = true; } else if isSomeOtherError(err) { return err } } } while(tryagain) }

obviously, depending on your needs, you could limit the retry and just return an error if the sequence fails, but something like the above should solve the problem w/o producing new edge cases.

Recommend

  • OneToOne bidirectional mapping foreign key auto fill
  • MongoError: getaddrinfo ENOTFOUND undefined undefined:27017
  • PXAction seemingly does nothing
  • Peer to peer/adaptive payments with paypal [closed]
  • View Paypal shopping cart contents on my site
  • Install phpMongo Drivers on windows
  • pymongo replication secondary readreference not work
  • What is the use of a session store?
  • Check all values in string[] for length?
  • Ember.js model to be organised as a tree structure
  • How do I signal completion of my dataflow?
  • RxJava debounce by arbitrary value
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • How can I extract results of aggregate queries in slick?
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • Parsing a CSV string while ignoring commas inside the individual columns
  • onBackPressed() not being executed
  • Jackson Parser: ignore deserializing for type mismatch
  • Is there a way to do normal logging with EureakLog?
  • OpenGL ES texture problem, 4 duplicate columns and horizontal lines (Android)
  • Avoid links criss cross / overlap in d3.js using force layout
  • Asynchronous UI Testing in Xcode With Swift
  • MongoDB in PHP using aggregate to group by _id is null not working
  • Can Jackson SerializationFeature be overridden per field or class?
  • Validaiting emails with Net.Mail MailAddress
  • Perl system calls when running as another user using sudo
  • Which linear programming package should I use for high numbers of constraints and “warm starts” [clo
  • Javascript + PHP Encryption with pidCrypt
  • Redux, normalised entities and lodash merge
  • ActionScript 2 vs ActionScript 3 performance
  • Large data - storage and query
  • How can I estimate amount of memory left with calling System.gc()?
  • SVN: Merging two branches together
  • Hibernate gives error error as “Access to DialectResolutionInfo cannot be null when 'hibernate.
  • Android Studio and gradle
  • Why joiner is not used after Sequence generator or Update statergy
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • Turn off referential integrity in Derby? is it possible?
  • How to get NHibernate ISession to cache entity not retrieved by primary key