Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Join 2 collections

Hi,

I have a little problem, I want to do that in Mongo.

select * from profiles where profiles._id in (select id_dst from likes where id_src = 1)

profiles contain all informations about my users (+/- 50.000 documents) (with Geo info)
likes is a table with the links between 2 profiles (A like B, B like C, C like A, …). (+/- 1.500.000 documents)

In Mongo I can do that :

  1. From the likes collection
db.likes.aggregate([{
      $match: {
          id_src: 1
      }
  }, {
      $lookup: {
          from: 'profiles',
          localField: 'id_dst',
          foreignField: '_id',
          as: 'profile'
      }
  }, {
      $project: {
          profile: {
              $arrayElemAt: ['$profile', 0]
          }
      }
  }, {
      $replaceRoot: {
          newRoot: "$profile"
      }
  }])

But in this case I can’t use the $geoNear :frowning:

  1. From the profiles collection
db.profiles.aggregate([{
      $lookup: {
          from: 'likes',
          let: {
              ref_id: '$_id'
          },
          pipeline: [{
              $match: {
                  $expr: {
                      $and: [{
                              $eq: ['$id_dst', '$$ref_id']
                          },
                          {
                              $eq: ['$id_src', ObjectId('5eb2564968c6e15a3a681ef8')]
                          }
                      ]
                  }
              }
          }],
          as: 'likers'
      }
  }, {
      $match: {
          likers: {
              $ne: []
          }
      }
  }])

But in this case it’s very slow, because the system must be merge the 50.000 with the 1.500.000, and only after the system can excluded the 99.99999% of unneeded documents :frowning:

  1. Add a sub document into profiles with the likes, but in this case the update are more slow, and the request “who’s like me” it’s slow

Do you have a solution to do that ?

Thanks