MongoDB: Delete 'orphaned' documents?

1k views Asked by At

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?

1

There are 1 answers

0
must_ache On

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.

db.values.aggregate([
  {
    $lookup: {
      from: "results",
      localField: "resultId",
      foreignField: "id",
      as: "resultDocument"
    }
   },
   { $match: { resultDocument: {$size:0} }}
])

This way, you have identified your orphaned documents and can delete them afterwards.