我有如下记录
[
{
_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'}
]
}
]3查询时,我希望计数为userAndTeam = [1, 2],即如果记录有usr.id as 1 or 2,则获取这些记录。2查询时,我希望计数为userAndTeam4 = [1, 4],即如果记录有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的用户获得了
有人能引导我解决这个问题并得到预期的计数吗?
发布于 2018-03-29 10:24:58
您可以尝试在下面进行聚合:
db.col.aggregate([
{
$unwind: "$usr"
},
{
$project:{
"userId": "$usr.id",
"count-2": {
$cond: {
if: { $in: [ "$usr.id", userAndTeam ] },
then: 1,
else: 0
}
},
"count-4": {
$cond: {
if: { $in: [ "$usr.id", userAndTeam4] },
then: 1,
else: 0
}
}
}
},
{
$group: {
_id: "$_id",
"count-2": { $max: "$count-2" },
"count-4": { $max: "$count-4" }
}
},
{
$group: {
_id: null,
"count-2": { $sum: "$count-2" },
"count-4": { $sum: "$count-4" }
}
}
])代码中所缺少的是,您希望为每个0或1设置每个_id,因此您需要通过_id对每个组的$max值进行分组,如果任何元素与数组匹配,则为0,如果没有匹配的1元素,则为0。
https://stackoverflow.com/questions/49550175
复制相似问题