Search code examples
mongodbmongodb-querynosqlaggregation-frameworkaggregation

how to find most mutual friend or follower?


I have a list of friends and those friends have a list of their own friends and I need to calculate the most mutual friend for me. I am using MongoDB as a database.

my user schema

    id: {
    type: String,
    require: true,
    unique: true
},
    followers: [{
        type:mongoose.Schema.ObjectId,
        ref: 'User'
    }],
    following: [{
        type:mongoose.Schema.ObjectId,
        ref: 'User'
    }]
})

I am not sure but is it possible to achieve this feature using aggregation in MongoDB.


Solution

  • You can use this aggregation query.

    1. Find both users based on _id. ( this should return 2 documents).

    2. Group both the documents using $first and $last. ( this will combine both documents).

    3. Use Project stage to find the count ($setIntersection will give you mutual elements of the array, then you can compute the size).

      [{
      '$match': {
          '_id': {
              '$in': [
                  ObjectId('60d90d5163326a4760b68ee3'), ObjectId('60d90d5dc498a4477a039d28')
              ]
          }
       }
      }, {
      '$group': {
          '_id': 0, 
          'set1': {
              '$first': '$following'
          }, 
          'set2': {
              '$last': '$following'
          }
       }
      }, {
      '$project': {
          'mutual': {
              '$setIntersection': [
                  '$set1', '$set2'
              ]
          }, 
          'count': {
              '$size': {
                  '$setIntersection': [
                      '$set1', '$set2'
                  ]
              }
          }
       }
      }]