I am trying to delete orphaned documents in mongodb, which cross collections. In the collection 'values', I have documents like this:
value:
{
resultId: <ObjectId>
...other data..
}
which reference documents in the collection 'results':
result:
{
_id: <ObjectId> //the resultId
}
A number of 'result' documents have been deleted, resulting in orphaned 'value' documents. How can I find all orphans and delete them?
What you will want to do is build up an aggregate pipeline and use the
$lookup
operator to fetch the corresponding result document. Then, add a$match
operator to your aggregate pipeline to filter those that don't have corresponding result object.This way, you have identified your orphaned documents and can delete them afterwards.