Dom
Dom

Reputation: 31

Mongodb - Find coupled documents, where A is following B and B is following A

I'm trying to find all users in my database that follow the user back.

The followers collection has 3 fields: _id, _t, _f.

When a user follows another user it adds their user ID to _f and the id of the target user to _t

I need to query all documents where the inverse for _f, _t exist in the database and retrieve all users id's that follow back.

EXAMPLE:

{
  _id: "62a0f3fb362c239460e8ee09",
  _f: "611531d23039d93be3bf2e2a",
  _t: "61bdd50570a6a12866e3297f",
  createdAt: "2022-06-08T19:03:35.246Z"
},
{
  _id: "62a0f3fb362c239460e8ee09",
  _f: "61bdd50570a6a12866e3297f",
  _t: "611531d23039d93be3bf2e2a",
  createdAt: "2022-06-08T19:03:35.246Z"
}

If these two documents existed in a collection I would want the query to retrieve them both so that I could pull the _f value, thus retrieve all the users that I follow AND follow me back.

Upvotes: 3

Views: 36

Answers (1)

nimrod serok
nimrod serok

Reputation: 16033

There is a difference between finding all couples, and finding all couples that a specific user is a part of them.

If you want to find all couples, you can use an aggregation pipeline with $lookup:

db.followers.aggregate([
  {
    $lookup: {
      from: "followers",
      let: {f: "$_f", t: "$_t"},
      pipeline: [
        {
          $match: {
            $expr: {$and: [{$eq: ["$_t", "$$f"]}, {$eq: ["$_f", "$$t"]}]}
          }
        },
        {$project: {_id: 1}}
      ],
      as: "hasCouple"
    }
  },
  {$match: {$expr: {$gt: [{$size: "$hasCouple"}, 0]}}},
  {$set: {hasCouple: {$first: "$hasCouple._id"}}}
])

See how it works on the playground example - all couples

If you want just all couples that a user x is a part of them, add a $match step at the start, to get focused results:

 {$match: {_f: x}},

See how it works on the playground example - specific user

Upvotes: 1

Related Questions