How to construct an aggregation pipeline to filter documents based on field values in other documents?

If the document collection contains:

{ _id: "1", name : "doc1", myDocRefId : "" }
{ _id: "2", name : "doc2", myDocRefId : "" }
{ _id: "3", name : "doc3", myDocRefId : "1" } 

I want to construct an aggregation returning only the documents not being referenced by any other documents via my myDocRefId field. For this collection I would like to return:

{ _id: "2", name : "doc2", myDocRefId : "" }
{ _id: "3", name : "doc3", myDocRefId : "1" }

Doc 1 is removed in the aggregation because doc 3 has a reference to it.

How can this be done in an aggregation pipeline?

Upvotes: 1

Views: 97

Answers (1)

Valijon
Valijon

Reputation: 13103

Try this one:

db.collection.aggregate([
  {
    $lookup: {
      from: "collection",
      localField: "_id",
      foreignField: "myDocRefId",
      as: "tmp"
    }
  },
  {
    $match: {
      tmp: {
        $size: 0
      }
    }
  },
  {
    $unset: "tmp"
  }
])

MongoPlayground | $graphLookup

Upvotes: 1

Related Questions