MongoDB Increment or Upsert -


given following document structure:

{          '_id': objectid("559943fcda2485a66285576e"),          'user': '70gw3',          'data': [             {               'date': isodate("2015-06-29t00:00:00.0z"),               'clicks': 1,             },             {               'date': isodate("2015-06-30t00:00:00.0z"),               'clicks': 5,             },           ]     } 

how can increment clicks value of 2015-06-30 , increase if doesn't exists [the whole document or specific date], make equals 1?

unfortunately not possible achieve goal within single query. instead can following

var exists = db.yourcollection.find(     {'_id': objectid("559943fcda2485a66285576e"), 'data.date': <your date>} ).count() 

this query return number of documents have specified _id , object specified date in data array. _id field unique, @ 1 result. if such element not exist in data array, not result. thus, have following cases:

  • exists == 1: there is element specified date
  • exists == 0: there is no element specified date

then can become condition:

if (exists) {     db.yourcollection.update({_id: <your id>, 'data.date': <your date>}, {$inc: {'data.$.clicks': 1}}) } else {     if (db.runcommand({findandmodify: 'yourcollection', query: {_id: <your id>, 'data.date': {$ne: <your date>}}, update: {$push: {data: {date: <your date>, clicks: 1}}}}).value) {          db.yourcollection.update({_id: <your id>, 'data.date': <your date>}, {$inc: {'data.$.clicks': 1}})     } } 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -