Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-38729

Make $setOnInsert work with upserts and positional array updates

    • Type: Icon: Improvement Improvement
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Querying
    • None

      Right now when doing an upsert with an update of a specific array element, MongoDB will create a new document with an "embedded doc":

      db.m1.update({"_id.reportingPeriod":new Date("2018-12-02T00:00:00Z")},{$set:{"daily_stats.2":10},},{upsert:true})
      

      I think it will be beneficial for users to be able to tell MongoDB that the "daily_stats" field should be an array when creating a new document. Intuitively, $setOnInsert could do the trick instead of complaining of the conflict:

      > db.m1.update({"_id.reportingPeriod":new Date("2018-12-02T00:00:00Z")},{$set:{"daily_stats.2":10}, $setOnInsert:{daily_stats:[]}},{upsert:true})
      WriteResult({
      	"nMatched" : 0,
      	"nUpserted" : 0,
      	"nModified" : 0,
      	"writeError" : {
      		"code" : 40,
      		"errmsg" : "Updating the path 'daily_stats' would create a conflict at 'daily_stats'"
      	}
      })
      

            Assignee:
            asya.kamsky@mongodb.com Asya Kamsky
            Reporter:
            alex.komyagin@mongodb.com Alexander Komyagin (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            8 Start watching this issue

              Created:
              Updated:
              Resolved: