简体   繁体   中英

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 _id s 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM