Home > OS >  mongodb : add new property to each object of an array property of every document
mongodb : add new property to each object of an array property of every document

Time:08-31

I have the following collection in mongo :

     // 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 collection 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

CodePudding user response:

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

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

Demo @ Mongo Playground

  • Related