Although this would not be possible, MongoDB is not suitable for this scenario.
The reason is that MongoDB does not do JOINs. When you need a query that spans multiple documents, you need a separate query for each document.
In your example, each user document will have an array with the _id their friends. To find "all friends of UserA friends who are also UserB friends", this would mean that you:
- find userA and get his friends array
- find all users in this array and get their friendly arrays
- find all users in these arrays that have UserB in their friends array
These are the three queries you must complete. Between each of these queries, a result set should be sent to the application, the application should formulate a new query and send it back to the database. The result returned from the second query can be quite large, which means that the third query can take some time.
tl; dr: Use the right tool for the job. When your data is graph-based and you want to run graph-based queries on it, use the graph database.
source share