Austin Hunter
Austin Hunter

Reputation: 394

MongoDB editing a document

Firstly let me explain what I am working with. So I have a collection of userProfiles that are modeled like in the plnkr. I am also have a function that is being passed a array of edited topics. I then need to search the userProfiles collection for a matching topicID and replace the topics section of the document. Not the entire document. I know of the collection.replace(). But that replaces the entire document. I need to replace just like half of it. So maybe I need to use findOneAndUpdate()? Im not sure. I am new to Mongo.. I have made a plnkr for code reference. plnkr

Upvotes: 1

Views: 104

Answers (2)

Lakmal Vithanage
Lakmal Vithanage

Reputation: 2777

You can use $set for this.

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

Upvotes: 1

andresk
andresk

Reputation: 2845

If you just need to replace the topics you can simply use the update method. And if you need to edit more than one userProfile, set multi to true (in case more than one user has the desired topicId).

Upvotes: 2

Related Questions