【发布时间】:2018-03-29 07:19:48
【问题描述】:
我有如下记录
[
{
_id : 1, nm : 1,
usr:[
{id : 1, ty : 'team'},
{id : 2, em : 'a'},
{id : 3, em : 'b'}
]
},
{
_id : 2, nm : 2,
usr:[
{id : 2, em : 'a'},
{id : 3, em : 'b'}
]
},
{
_id : 3, nm : 3,
usr:[
{id : 1, ty : 'team'},
{id : 3, em : 'b'}
]
},
{
_id : 4, nm : 4,
usr:[
{id : 3, em : 'b'}
]
}
]
- 当使用
userAndTeam = [1, 2]查询时,我希望计数为3,即如果记录具有usr.id as 1 or 2,则获取这些记录。 - 当使用
userAndTeam4 = [1, 4]查询时,我希望计数为2,即如果记录有usr.id as 1 or 4,则获取这些记录。
我尝试使用$unwind,这使得第一种情况的计数为4,因为$unwind为第一条记录创建了3条记录,下面的查询与其中2条记录匹配。
我尝试过的查询:
var userAndTeam = [1, 2] //User id and team id. Record should match one of the ids.
var userAndTeam4 = [1, 4]
[{
$unwind: '$usr'
},
{
$project:{
'count-2' : {$cond: {
if: {$in : ['$usr.id',userAndTeam]},
then: 1,
else: 0
}},
'count-4' : {$cond: {
if: {$in : ['$usr.id',userAndTeam4]},
then: 1,
else: 0
}}
}
}
]
输出:
预期用于 ID 为 2 - 'count-2' 的用户:3
得到 id 为 2 - 'count-2' 的用户:4
预期用于 ID 为 4 - 'count-4' 的用户:2
得到 id 为 4 - 'count-4' 的用户:2
有人可以指导我解决这个问题并获得预期的计数吗?
【问题讨论】:
-
您可能需要查看“我的记录如下”部分,因为您不太清楚如何从提供的数据集。
-
@AlexBlex 请立即检查问题。我希望我的问题和要求现在更清楚了。
标签: mongodb aggregation-framework aggregation