Reputation: 3459
If I have a collection Friends
like:
{'_id': ObjectId('abcdef1'), 'user': 'Jim', 'user2': 'Jon'}
{'_id': ObjectId('abcdef2'), 'user': 'Jim', 'user2': 'Fred'}
{'_id': ObjectId('abcdef3'), 'user': 'Jon', 'user2': 'Jim'}
and I want a query that gets all people that are friends with me, and a boolean for whether or not I'm friends with them. I was hoping for some find statement that would be like:
Find all people I'm friends with and add a field that says whether they're friends with me
My expected output would be for the User Jim:
{'friends': {'user': 'Jon', 'friends_with_me': true,
{'user': 'Fred', 'friends_with_me': false,}}
Upvotes: 3
Views: 1140
Reputation: 75934
With the latest Mongo 3.4 version you can make use of $graphLookup to identify the relationship.
db.Friends.aggregate([{
$match: {
user: 'Jim'
}
}, {
$graphLookup: {
from: 'Friends',
startWith: '$user2',
connectFromField: 'user2',
connectToField: 'user',
maxDepth: 0,
as: 'relationship'
}
}, {
$project: {
_id: 0,
user: '$user2',
friends_with_me: {
$cond: [{
$eq: [{
$size: "$relationship"
}, 0]
}, false, true]
}
}
}])
Upvotes: 6