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

    XMLWordPrintable

    Details

    • Type: New Feature
    • Status: Closed
    • Priority: Major - P3
    • Resolution: Duplicate
    • Affects Version/s: None
    • Fix Version/s: None
    • Component/s: Querying
    • Labels:
      None

      Description

      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}]}
      

        Attachments

          Issue Links

            Activity

              People

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

                Dates

                Created:
                Updated:
                Resolved: