Friday, August 24, 2018

Updating Embedded Array And Objects In Mongo

In Mongo I have a collection of post and each post has comments that are embed with a user id, user name and user email.

- post
    - comments
           - user_id name email

I was wondering how can I update the all the emails that are associated with a certain id?

Solved

Currently, you would have to retrieve comments first, and then update emails.

Depending on which client you use, here is a mongoid example:

comments = post.comments
comments.update_attributes(:email => "a@b.c")

Also there is already a "Use positional operator to update all items in an array" JIRA that, once implemented, will allow you to do it in one shot.


Have you tried the $ positional operator, its the only way to update the matching sub(embedded docs) docs.


No comments:

Post a Comment