Update only specific fields

Hi All,

I have the following code:

   Company.updateOne(
    { 'configItems.id': { $in: autotask } },
    {
      $set: {
        'configItems.status.linked.state': true,
        'configItems.status.linked.linkId': true,
      },
    }
  )

However i get error:

MongoError: Cannot create field 'status' in element {configItems: .....

If i try this with positional operater “$” i get error saying that i cant use $ in key name

I have created a question on stack overflow too but no answers yet.
https://stackoverflow.com/questions/68940477/mongo-db-update-array-within-document

Could anyone help me understand where the error might be?

Tahnk you

Welcome to the MongoDB Community Forums @Jakub_Koudela!

Dot notation in MongoDB is used for indexing into both arrays and embedded documents. The Cannot create field error suggests there is a problem updating your document based on the structure and the field paths you are trying to set. Your Stack Overflow post mentions updating an object within an array, but we need to see the document for context.

Please provide some more information to help reproduce your issue:

  • Sample document
  • Version of Node.js driver
  • Version of MongoDB server

Thanks,
Stennie

Hi, thank you for tour reply.

I have sorted it out now.

For what its worth, i have used updateMany() instead and it works.

Id like to understand why it doesnt work with updateOne()

Hi @Jakub_Koudela,

Great that you were able to find a solution! If you’d like some help trying to understand why the original approach didn’t work, please provide the further details I requested so we can try to reproduce this.

Thanks,
Stennie