Tmb
Tmb

Reputation: 470

Update a given mongo field in unknown parents fields

Lets say I have a document structured like that :

datas: {
    foo: {
        ...
        keytoupdate: [...]
    },
    whatever: {
        ...
        keytoupdate: [...]
    },
    anystring: {
        ...
        keytoupdate: [...]
    },
    ...: {
        ...
        keytoupdate: [...]
    }
}

I know that :

I want to update each "keytoupdate" fields, no matter how many of them there are.

The question is: How can I do that ? Is there any magic operator like $ that does the same job for Array ?

Thank you !

Upvotes: 4

Views: 873

Answers (1)

Tmb
Tmb

Reputation: 470

I'll answer my own question : there is no way to do that, we can't play with dynamic keys, just forget about it ! But there are 2 workarounds :

  1. The best solution, as suggested by @chridam, is to redesign the schema to make an array of objects, where the keys are parts of the arrays, you can see this question for more details.
  2. If you can't, the other (but not good) solution is to make a request for each field that might be in your document, instead of trying to do this in one request. This is a very bad solution, especially if your document may have lots of fields, and you have to known which fields that could be in your documents. This is a bad solution, absolutely not optimized, but it has the merit of being simple to implement

Upvotes: 2

Related Questions