Reputation: 1570
I have a mongo database and several collections in it. I want to remove from collections all entiries that match, say, target_id. The trick is that I also have to remove entries "connected" to entries that match target_id.
For example
DB
Culture (_id, owner_id)
Document (_id, target_id)
Entity (_id, target_id)
Field (_id, entity_id)
Form (_id, target_id)
Question (_id, form_id)
Layout (_id, question_id)
Now, I can easilily remove all documents by
db.Document.remove( {"_id": ObjectId(target_id)});
So the first tricky part, is that some entry in Culture collection may have owner_id = document_id. So before I remove entity entry I have to also remove culture entry.
Second problem is that I can't directly access by target_id entries in field collection, because those fields can be found by entity_id.
So I'd like to write a script/query to run from mongo shell providing target_id and then remove all entries directly or indirectly "referenced" by target_id. I haven't had experience beyong simple find/delete by id, so this query got be stuck.
As far as I understand I can do this step by step, say, first find all entities:
db.Entity.find({ "$where" : "{"target_id" : ObjectId(target_id)}" });
The second step is to remove all cultures that have owner_id = entity id of every entity from query above. How can I run
db.Culture.find({ "$where" : "{"owner_id" : ObjectId(entity_id)}" });
Where entity_id iterate over all enties the the first query?
Upvotes: 0
Views: 200
Reputation: 5940
IIUC, you are looking for the $in operator.
Do this repeatedly down the hierarchy...
Example:
db.Culture.find({"owner_id" : {"$in":[set_of_entityids]" }});
Note you get bson ids from queries, so you probably don't need to prefix with ObjectId
HTH
Upvotes: 1
Reputation: 4550
One of the way of doing it using findAndMondify . You can update the document at the same time you will also get the Ids back . So you will mark the documents as ACTIVE = FALSE , and then get the Ids back in findAndModify . In the last just remove all the entries which is ACTIVE = FALSE. You can see how I have used in my application : http://devesh4blog.wordpress.com/2013/03/01/findandmodify-in-mongodb-a-practical-example/
Upvotes: 0