I have kind of graph connections in MongoDB:
{
from: ObjectID(user),
to: ObjectID(user)
}
if I want to get all users at depth 1, is easy:
db.connections.find({from:ObjectID(myUser)});
But when I want to find all users at depth 2, is hard: The foolish idea is "find all people at depth 1, then do a query like the previous one, for each person. No way, plus it would return also all circular paths.
e.g
1->2
2->1
1->3
2->4
results of user(1).findDepth2() would be 2,1,3,4 instead of 4.
The example in pseudo node.js:
var myFriends = db.connections.find({from:ObjectID(myUser)});
var friendAtDepth2 = [];
for(friend in myFriends){
// I find friends of each friend
var frendsOfFriend = db.connections.find({from:ObjectID(friend)});
for(friendOfFriend in frendsOfFriend){
if(friendAtDepth2.indexof(friendOfFriend)==-1
&& myFriends.indexof(friendOfFriend)==-1
&& myUser!=friendOfFriend){
// I haven't already found this user, so I it is actually at depth 2
friendAtDepth2.push(friendOfFriend);
}
}
}
But in this way, I do really a lot of queries, and I hope exist a kind of join query like in mysql helipng me doing this in one query only
Is a query like this feasible?