简体   繁体   English

MongoDB-使用javascript更新子文档

[英]MongoDB - Update subdocuments using javascript

The documents in my apps collection each contain a subcollection of users. 我的apps集合中的文档每个都包含一个用户子集合。 Now I need to update a single user per app given a set of _id s for the apps collection using javascript. 现在,我需要为每个应用程序更新一个用户,并使用javascript为apps集合提供了一组_id 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. 我不能为此使用常规调用update() ,因为插入的数据将使用存储在应用程序文档中的公共密钥进行加密。 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. 一种方法是找到所有应用程序,然后使用forEach()更新每个应用程序。 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. 简短的答案是不,您不能使用该文档中的值更新mongoDB中的文档。

Have a look at https://stackoverflow.com/a/37280419/5293110 for ideas other that doing the iteration yourself. 看看https://stackoverflow.com/a/372​​80419/5293110,了解除了自己进行迭代之外的其他想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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