如何在mongodb类别中返回布尔值 [英] How Do I return a boolean in a mongodb category
本文介绍了如何在mongodb类别中返回布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个收藏集Friends
,例如:
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
我的预期输出将是用户Jim的输出:
My expected output would be for the User Jim:
{'friends': {'user': 'Jon', 'friends_with_me': true,
{'user': 'Fred', 'friends_with_me': false,}}
推荐答案
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]
}
}
}])
这篇关于如何在mongodb类别中返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文