Home > Software design >  MongoDB find records with reverse match
MongoDB find records with reverse match

Time:07-06

I have the following structure to store user's like. For example, _id1 user likes user _id2 & _id3. Where the _id1 user is having a match with user _id2 only.

I need only records with a match.

Document Structure --

[
  {'from':'_id1', 'to':'_id2'},
  {'from':'_id1', 'to':'_id3'},
  {'from':'_id2', 'to':'_id1'},
]

Expected Output --

[
  {'from':'_id1', 'to':'_id2'},
  {'from':'_id2', 'to':'_id1'},
]

CodePudding user response:

You can $group on the "couple" and only then match those that were summed to be 2. The trick is to make sure the _id your grouping on is the same - I just did it with $cond and create the tuple [ _id1, _id2 ] where the smaller id is always first, like so:

db.collection.aggregate([
  {
    $group: {
      _id: {
        $cond: [
          {
            $gt: [
              "$from",
              "$to"
            ]
          },
          [
            "$to",
            "$from"
          ],
          [
            "$from",
            "$to"
          ]
        ]
      },
      sum: {
        $sum: 1
      },
      roots: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $match: {
      sum: {
        $gt: 1
      }
    }
  },
  {
    $unwind: "$roots"
  },
  {
    $replaceRoot: {
      newRoot: "$roots"
    }
  }
])
  • Related