MongoDB编辑文档

时间:2016-10-21 18:33:43

标签: javascript mongodb

首先让我解释一下我在做什么。 所以我有一个userProfiles的集合,就像在plnkr中一样建模。 我也有一个正在传递一系列已编辑主题的函数。然后,我需要在userProfiles集合中搜索匹配的topicID并替换文档的主题部分。不是整个文件。我知道collection.replace()。但这取代了整个文件。我需要更换一半。那么也许我需要使用findOneAndUpdate()?我不确定。我是Mongo的新手。我已经为代码参考做了一个plnkr。 plnkr

2 个答案:

答案 0 :(得分:2)

如果您只需要替换主题,只需使用update方法即可。如果您需要编辑多个userProfile,请将multi设置为true(如果有多个用户具有所需的topicId)。

答案 1 :(得分:1)

您可以使用$set

db.userProfiles.update(
   { "UserTopics.topicID": "abc"},
   { $set: { "UserTopics.$": editedTopic } }
)