How to achieve "Insert or Increment" in one MongoDB query? -


i want write query in mongodb insert object in document if doesn't exist or increment field of if exists in specified document. there 2 queries follows example:

documents structures:

     movies:      {          integer _id,          string name,          array(object) watchinglist          [             {                 integer userid,                 integer watchtimes             }             .....          ]      } 

insert query:

db.movies.update({_id:x}, {$push: {watchinglist:{userid:y,watchtimes:1}}}); 

increment query:

db.movies.update({_id:x,"watchinglist.userid":y},{$inc:{"watchinglist.$.watchtimes":1}}); 

how can combine them 1 or more queries acheive requirement?

from question understand need generic update method both insert , update array.it can done using dummy object in array last element , update element in case of insert.

i'm giving here example : add dummy object array :

      > db.m4.update({_id:"id"},{"$addtoset":{watchinglist:{userid:"last",watchtimes:0}}},true,true)       > db.m4.find()         { "_id" : "id", "watchinglist" : [ { "userid" : "last", "watchtimes" : 0 } ] } 

//now below query handle both insert , update condition :

     db.m4.update({_id:"id","watchinglist.userid":{"$in":["p","last"]}},{$inc:{"watchinglist.$.watchtimes":1},"$set":{"watchinglist.$.userid":"p"}}); 

remember run first dummy addition before each update statement.or can add large number of dummy objects itself


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -