Search code examples
arraysdatabasemongodbsubdocument

MongoDB - Update subdocuments using javascript


The documents in my apps collection each contain a subcollection of users. Now I need to update a single user per app given a set of _ids for the apps collection using javascript. I cannot use a regular call to update() for this, as the data inserted will be encrypted using a public key stored within the app document. Therefore the data written into the user-subdocument is dependant on the app-document it is contained in. Pseudo-code of what I need to do:

foreach app in apps:
    app.users.$.encryptedData = encrypt(data, app.publicKey)

One way to do it would be to find all the apps and then use forEach() to update every single app. However, this seems to be quite inefficient to me, as all the app-documents would have to be found twice in the database, one time to gather all of them and then another time to update every single document. There has to be a more efficient way.


Solution

  • The short answer is that no, you can not update a document in mongoDB with a value from that document.

    Have a look at https://stackoverflow.com/a/37280419/5293110 for ideas other that doing the iteration yourself.