It was my understanding that when you destroy a parent document in Mongo that you also destroy its children and it will cascade down the chain until all referenced documents have been removed.
I have a collection structure like the following
class A
include Mongoid::Document
field :name, :type => String
has_many :bs
end
class B
include Mongoid::Document
field :name, :type => String
has_many :cs
end
class C
include Mongoid::Document
field :name, :type => String
end
I came across a situation in my code where I needed to delete one of Class A and all of its relevant documents. Since Each of these models were based of Mongoid I used the destroy_all method like so
a = A.where({'_id' => "123456789"})
a.bs.destroy_all
=> 'however many a's I had'
From reading the documentation I thought that each of the referenced documents would be removed aswell.
Unfortunately what has happened is all my class b’s are gone and I have a bunch of orphaned class c’s in my database.
So:
A) Assuming destroy_all doesn’t do what I thought it would. Is there anything that can be used to actually delete a parent and all of its referenced documents in mongoid?
B) Although I performed this operation on a local machine, I would still like to know, is there any way to remove orphan documents from an altered collection?
Only when it is a single document. You are showing a structure of many documents.
I am not a Ruby programmer and I have never used mongoid however it seems that
destroy_allis essentiallyremovethat matches more than one document as is supported by the docs: http://two.mongoid.org/docs/persistence/standard.html#destroy_allI am guessing that if you wish to remove the children as well you will be required to manually specify them since MongoDB has no relational behaviour and so has no ability to cascade your “relations” on its own.
The only real way, I would say, to remove orphaned documents is most likely the hard way by going through all distinct references to the documents parents within the child collection querying the parent collection to see if it exists. If it does not exist, remove it.