Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 want to modify the array of embedded documents in-memory - and then persist all changes with a single UPDATE operation. Specifically, I'd like to:

  1. Modify arrays of embedded documents (add embedded doc / remove embedded doc / edit embedded doc / etc).
  2. Possibly make other changes to the TLD.
  3. Persist all changes with a single database call.
like image 645
fedenusy Avatar asked May 16 '14 00:05

fedenusy


People also ask

How do I remove a field from an embedded document in MongoDB?

In MongoDB, you can use the $unset field update operator to completely remove a field from a document. The $unset operator is designed specifically to delete a field and its value from the document.

What is embedded document in MongoDB?

MongoDB provides you a cool feature which is known as Embedded or Nested Document. Embedded document or nested documents are those types of documents which contain a document inside another document.

How do I update an embedded file in MongoDB?

Update Documents in an ArrayThe positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.

How do I query embedded files in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.


1 Answers

It is possible to remove an embedded document using Mongoid without saving. The trick is to make your changes from the parent object using assign_attributes. For exmaple:

class MyParent
  include Mongoid::Document

  field :name, type: String
  embeds_many :my_children

  def remove_my_child(child)
    assign_attributes(my_children: my_children.select { |c| c != child })
  end
end

class MyChild
  include Mongoid::Document

  embedded_in :my_parent

  def remove
    parent.remove_my_child(self)
  end
end

my_parent = MyParent.first
my_first_child = my_parent.my_children.first

# no mongo queries are executed
my_first_child.remove

# now we can make another change with no query executed
my_parent.name = 'foo'

# and finally we can save the whole thing in one query which is the
# reason we used an embedded document in the first place, right?
my_parent.save!
like image 80
Stephen Crosby Avatar answered Sep 20 '22 01:09

Stephen Crosby