Adding field to every object in array

I am attempting to add a new field into every object within an array only when that field does not already exist. I am trying to use updateMany but the below script does not seem to work…

The logic should be, for every object in the array ss_characteristics, if the field new_field is not present, add it with an empty string value.

Please help!

const updateResult = await Form.updateMany(
  {},
  { $set: { "ss_characteristics.$[elem].new_field": '' } },
  { arrayFilters: [{ "elem.new_field": { $exists: false } }] }
);

console.log('updateResult: ', util.inspect(updateResult, false, null));
// that logs the below:
// updateResult:  { acknowledged: false }
const all_forms = await Form.find({})
// logging all_forms will give me something similar to below:

[
  {
    ss_characteristics: [
      { name: 'test 1' },
      { name: 'test 2', new_field: 'No'}
    ]
  },
  {
    ss_characteristics: [
      { name: 'test 3' , test_field: ''},
      { name: 'test 4' },
    ]
  },
  {
    ss_characteristics: []
  }
]

Hello @Eden_Hikri, Welcome to the MongoDB community forum,

Your query looks good, see the working playgroud.

Can you please check your implementation, might be you are missing something in your nodejs code.

Thanks! What could be the reason that:

console.log('updateResult: ', util.inspect(updateResult, false, null));
// logs the below:
// updateResult:  { acknowledged: false }

I am struggling to traceback the error more than acknowledged: false. Using other methods works completely fine! Even updateMany works but not this particular snippet.

You need to provide more details:

  • version of Mongodb server
  • version of MongoDB/mongoose npm
  • your schema/model code if you have used Mongoose npm

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.