In mongodb it's easy to make at upsert
, meaning update-or-insert by calling
db.collection.update({criteria}, {updated fields}, true)
The third parameter means - insert a new document if the document doesn't exist yet. So, for example, the following will insert a new document for the user if there's no document for that user yet, and will update it if it already exists:
db.users.update({user_id: '1234'}, {user_id: '1234', name: 'Ran'}, true)
But What If - you want to - not insert a predefined value, but instead - increment a counter? You have a visit_count for each user, and you'd like to increment that count if there's already a document for that user's visit count, or insert 1 if it's the first time. Ideally, you'd like to do something like this:
db.users.update({user_id: '1234'}, {user_id: '1234', $inc: {visit_count: 1}}, true)
Unfortunately, however, mongo doesn't work like this. Mongo does not allow upserts in combination with $inc (or other atomic operations). Atomic operations are nice b/c you're guaranteed that the counter's (in this case counter) value will remain consistent in light of multiple concurrent updates. So how do you make an "increment if the document already exists, and insert if it doesn't"?
Here's the trick I found out yesterday (and to be fair, I'm pretty green to mongo, so maybe there's a better one). Please see the file mongo-insert-or-incr.js below.
its not working when we do multiple increment with negative value (-1.23121). it will subtract but also increase decimal value. In end you will value like 0e-14 . Any solution for this .
I am working on some kind of trading platform. So i have maintain balance of account of users. When trading happen, order are settle, at that time transactions are created very fast on same account.
So I am using $inc function to add or subtract amount from user accounts. I faced lots of issue because when i was subtracting fractional values e.g. 0.001 from 0.003 then $inc function create issue. i was not getting correct value.
Now my balance field data type is Decimal128. my previous issue was resolved but it convert value like this .e.g 1.45057300000000. if i keep subtracting amount from this balance. Mongodb convert it into
0E-14.
Anyone can help me. I want my amount maximum with 6 decimal and correct amount. if i have 0.00000001 this much balance in account then database will show me same value.
Is it possible??????
If someone help me. i will appreciate