How Do I return a boolean in a mongodb category

梦想的初衷 提交于 2020-01-15 06:05:11

问题


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,}}

回答1:


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]
        }
    }
}])


来源:https://stackoverflow.com/questions/40918688/how-do-i-return-a-boolean-in-a-mongodb-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!