fedenusy fedenusy - 5 months ago 88
Ruby Question

Can I remove an embedded document in Mongoid without persisting?

Definitely related to this question, but since there was no clear answer, I feel like I should ask again. Is there any way to remove an embedded document from a Mongoid embeds_many relationship, without persisting?

I understand that Mongoid models itself after ActiveRecord. While I don't necessarily agree with the design decision, I'm not trying to debate the ODM's API. What I'm trying to figure out is whether I can use this wonderfully polished ODM to modify an array of embedded documents in-memory - and then persist all my changes with a single UPDATE operation.

One of the nicer things about Mongo, in my opinion, is its ability to store huge documents with complex embedded structures. It would be a shame if I couldn't model my data in a 'Mongonic' way just because my ODM decided MongoDB didn't fit the Rails mold.

So, ladies and gents, I would love any practical advice on how to:


  1. Modify an array of embedded documents (add / remove / modify / etc).

  2. Possibly make other changes to the TLD.

  3. Persist all changes with a single database call.


Answer

After two more years of using Mongoid, I've learned there's no operator for what I was trying to achieve. Removing an embedded document with Mongoid always results in a database call.

In situations like this one, it's easier to bypass Mongoid and use the mongo-ruby-driver directly.

Comments