Find orhphaned DBRef in collection

2.6k views Asked by At

Is there any easy way to find orphaned references in query? I've got a collection of elements having parent reference. After some parents was removed I'd like to search elements that pointed to them, i.e. those that have hanging references.

I tried various syntaxes but none worked.

3

There are 3 answers

0
Vinit Bothra On
db.childCollection.find().forEach(function(f) {
    if(f.refKey && db.parentCollection.find({ "_id": f.refKey.$id}).count() != 1) {
        db.childCollection.remove({ _id: f._id });
    }
});

this has worked very peacefully for me..

2
Andrew Orsich On

No isn't, since mongodb is non-relational you need to find all relations yourself. All drivers resolving references at client side by making request for any reference. In your case you need to go through all categories and try to load parent in case if parent not exists - remove child or do whatever you want. Dbref documentation

0
Andrew Newdigate On

Presuming:

  • the parent collection is parentCollection,
  • the child collection is childCollection
  • the child references the parent through childCollection.parentRefId,

Then you could delete all dangling child objects by issuing the following command to mongo:

db.childCollection.find().forEach(function(f) { 
    if(f.parentRefId && !db.parentCollection.findOne({ _id: f.parentRefId})) {        
        db.childCollection.remove({ parentRefId: f.parentRefId });
    }
});