在集合中查找orhphaned DBRef

1 reference mongodb dbref

有没有简单的方法来查找查询中的孤立引用?我有一组具有父参考的元素.在删除了一些父母后,我想搜索指向它们的元素,即那些有挂引用的元素.

我尝试了各种语法,但都没有.

And*_*ate 5

假设:

  • 父集合是parentCollection,
  • 孩子的收藏是 childCollection
  • 孩子引用父母通过childCollection.parentRefId,

然后,您可以通过向mongo发出以下命令来删除所有悬空子对象:

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