Search code examples
arraysmongodbmongodb-querymongodb-update

MongoDB - Add new property to each object in an array property for each document


I have the following collection in MongoDB:

// document 1
{  
  elements:[
    {
      prop1:true,
      prop2:false,
    },
    {
      prop1:true,
      prop2:false,
    }
  ]
},
// document 2
{

  elements:[
    {
      prop1:true,
      prop2:false,
    },
    {
      prop1:true,
      prop2:false,
    }
  ]
}

I want to update every element of elements collection of every document in the following way :

I want to add the property3: true to get:

// document 1
{  
  elements:[
    {
      prop1:true,
      prop2:false,
      prop3:true -> added property
    },
    {
      prop1:true,
      prop2:false,
      prop3:true -> added property
    }
  ]
},
// document 2
{

  elements:[
    {
      prop1:true,
      prop2:false,
      prop3:true -> added property
    },
    {
      prop1:true,
      prop2:false,
      prop3:true -> added property
    }
  ]
}

I tried to use the positional operator but it only updated the first element of elements array of each document:

await db.collection('MyCollection').updateMany(
  {
    elements: { $exists: true },
  },
  {
    $set: {
      'elements.$.property3': true,
    },
  }
)

I've tried to use the match, but it does not update anything:

await db.collection('MyCollection').updateMany(
  {
    elements: {
      $elemMatch: {
        prop1: {$exists:true},
      },
    },
  },
  {
    $set: {
      'prop3': false,
    },
  }
)

Thanks in advance for your help.


Solution

  • Use $[] all positional operator for elements.$[].property3.

    db.collection.updateMany({
      elements: {
        $exists: true
      },
      
    },
    {
      $set: {
        "elements.$[].property3": true
      },
      
    })
    

    Demo @ Mongo Playground