开发者

Find orhphaned DBRef in collection

Is there any easy way to find orphaned references in query? I've got a collection of elements hav开发者_StackOverflow中文版ing 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.


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 });
    }
});


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


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..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜