Fenrir
Fenrir

Reputation: 231

MongoDB Graph: Find A and B where A->B exists but B->A doesn't

I need to find a query where the statement in the title holds true with the training_sample db of mongodb. This is the data structure (directional graph):

{
    _id: ObjectId("56e9b39c732b6122f878f882"),
    airline: { id: 3778, name: 'Oman Air', alias: 'WY', iata: 'OMA' },
    src_airport: 'LHR',
    dst_airport: 'MCT',
    codeshare: '',
    stops: 0,
    airplane: 333
}

How do I do this?

Upvotes: 0

Views: 140

Answers (1)

nimrod serok
nimrod serok

Reputation: 16033

One option is to use $lookup:

  1. Using the $lookup pipeline to add to each document the opposite directions if exists
  2. $match only documents with empty opposite field
db.training_sample.aggregate([
  {$lookup: {
      from: "training_sample",
      let: {
        src_airport: "$src_airport",
        dst_airport: "$dst_airport"
      },
      pipeline: [
        {$match: {
            $expr: {$and: [
                {$eq: ["$src_airport", "$$dst_airport"]},
                {$eq: ["$$src_airport", "$dst_airport"]}
            ]}
        }}
      ],
      as: "opposite"
  }},
  {$match: {"opposite.0": {$exists: false}}},
  {$unset: "opposite"}
])

See how it works on the playground example

Upvotes: 1

Related Questions