Sample Header Ad - 728x90

MongoDB - Finding the degree of separation of two users

1 vote
1 answer
82 views
As suggested in this post, I'm proposing here my question. I have a MongoDB collections *spots* which has documents representing the friendship between two users { "_id": "64a337de4538a04610900f0c", "user1": "6468022102781d442b82afd7", "user2": "648c7b6b75231cd99e43d7ab", "areFriends": true } My goal is to write an aggregation which, given two user's IDs, returns the degree of separation of them. To be clear, something like that: - 1 = direct friends - 2 = friends of friends - 3+ ecc.. I came across the above example of $graphLookup, and now I am wondering how to implement something similar. The difference between my case and the other post is that my documents have not a unidirectional relation (from-to) but a bidirectional (user1, user2); so, there is not guarantee about that the wanted user is stored as user1 or user2. In other sections of my code, I solve this problem ordering the input ids or using conditions like this: $cond: { if: { $eq: ['$user1', userId] }, then: '$user2', else: '$user1', }, However, I've understood that conditions are not supported as filed (like *connectFromField*) in *$graphLookup* Is anyone have a clue on how to face this particular problem, it would be very appreciated. Thanks. **EDIT** this is a revised version of the aggregation pipeline proposed by Ray { $match: { user1: id1 } }, { $graphLookup: { from: 'spots', startWith: '$user1', connectFromField: 'user2', connectToField: 'user1', as: 'friendshipsViewLookup', depthField: 'degree', maxDepth: 2, }, }, { $unwind: { path: '$friendshipsViewLookup', preserveNullAndEmptyArrays: true, }, }, { $match: { 'friendshipsViewLookup.user2': id2 } }, { $project: { user1: 1, user2: '$friendshipsViewLookup.user2', degree: { $add: ['$friendshipsViewLookup.degree', 1], }, }, }, { $group: { _id: { user1: '$user1', user2: '$user2' }, minDegree: { $min: '$degree' }, }, }, { $project: { user1: '$_id.user1', user2: '$_id.user2', degree: '$minDegree', }, }
Asked by Niccolò Caselli (113 rep)
Oct 12, 2024, 12:16 PM
Last activity: Oct 14, 2024, 12:49 PM