I am writing a NodeJS program and I have hit a mongo wall. I am fairly new to writing complex MongoDB queries, and this is made more challenging by to my knowledge the NodeJS implementation for MongoDB does not yet include the 'createView()' function. Here is the structure of my database with example data:

------------------------------- _id | username | friends(array) ------------------------------- 1 | user1 | [user2] 2 | user2 | [user1, user3] 3 | user4 | [user3]

I am trying to write a query that checks if any of the friends of the friends of user1 are equal to the friends of user2. (In this scenario I would just like to return an array containing only 'user3')

I am having some difficulty making any progression with this problem, due to the inability to use views and having to use a single contained query to perform all of this logic. I know that mongo has some functions such as $graphlookup that might be useful for a solution but I am getting nowhere using them.

If anyone is interested, here is what I have got so far:

// Query1 this creates a view that // contains all usernames of friends of user4 db.createView( 'userView', collection, [{ $match: { username: user4 } }, { $unwind: "$friends" }, { $group: { _id: "$friends" } }, { $project: { _id: 1 } }] );

.

// Query2 this creates a view that // contains all usernames of friends of friends of user1 db.createView( 'friendsView', collection, [{ $match: { username: { $in: user1FriendsArray } } }, { $unwind: "$friends" }, { $group: { _id: "$friends" } }, { $project: { _id: 1 } }] );

.

// Query3 (this is incorrect) this query should find // any matches between the two views and return them within an array db.collection.aggregate([{ $group: { _id: { $and: [userView.$_id, friendsView.$_id] }, count: { $sum: 1 } } }, { $match: { count: 2 } }, { $project: { _id: 1 } }]);

I believe there will be a way to perform all of this is one single query, however I am having a total nightmare working out what that query might be.

Any assistance is greatly appreciated <3