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

update existing item or push a new item to an array in a document

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

      I want to update an object or push an object to an array in one query? For e.g if the document is

      {list: [{a: 1}]}
      

      I want to add a new object

      {b: 2}
      

      to list if this object doesn't exists in the list otherwise I want to update it.

      db.temp.update({
        list: {
          $exists: true
        }
      },
      {
        $set: { 
          "list.$[elem].a1": 10, 
        },
        $pushIfNoMatch: {
          list: {b: 2}
        }
      }, 
      {
        arrayFilters: [{
          "elem.a": {
            $ne: 1 
          }
        }], 
        
        multi: true,
        upsert: true
      })
      

      Since condition in arrayFilter will return false, $pushIfNoMatch operator will work and the new state of document will be

      {list: [{a: 1}, {b: 2}]}
      

      if we change the condition to $eq: 1, the $set operator will work and new state will be

      {list: [{a: 1, a1: 10}]}
      

            Assignee:
            ramon.fernandez@mongodb.com Ramon Fernandez Marina
            Reporter:
            dispareil Dinesh Chander
            Votes:
            0 Vote for this issue
            Watchers:
            7 Start watching this issue

              Created:
              Updated:
              Resolved: