$inc - default value (if not exists)

415 views
Skip to first unread message

Alexander Kit

unread,
May 5, 2014, 1:04:18 PM5/5/14
to mongod...@googlegroups.com
When we increment the value of the property, which not exists, mongo sets its initial value to zero and then performs the incrementation. Is it possible to define this `initial value`? 

My use case: There are dynamic properties, which can't be preinitialised/created on the first insert, but they all have the default start value: 100. So I would like to get this: 
{ $inc: { "en.points" : 5 } } 
to insert (if not exists): 105. 

I would also like to eliminate additional requests to the DB, to check if any value for the property exists.

Would anybody have some thoughts on this?

Thanks in advance,
Alex

Alexander Kit

unread,
May 5, 2014, 4:53:45 PM5/5/14
to mongod...@googlegroups.com

UPD. As for now, before incrementing I do one additional request:

db.users.update({
    '_id': ObjectId('id'),
    'en.points': { $exists: false }
}, {
    $set: { 
        'en': {
            points: 100,
            // ... other
        }
})
Reply all
Reply to author
Forward
0 new messages