我想知道如何使用聚合来执行此操作。 查找执行两次以上添加到购物车和商品查看事件的userId列表
收藏名称事件。
{
_id:1,
name:"Add To Cart",
userId:1
}
{
_id:2,
name:"Searched",
userId:2
}
{
_id:3,
name:"Add To Cart",
userId:1
}
{
_id:4,
name:"Item View",
userId:1
}
{
_id:5,
name:"Add To Cart",
userId:2
}
{
_id:6,
name:"Item View",
userId:1
}
我的查询-
db.getCollection("event").aggregate([ {$match:{$or:[{"name":"Add to
Cart"},{"name":"Item Viewed"}]}},
{$group:{_id: {userId:"$userId",name:"$name"},count:{$sum:1}}},
{$match:{count:{$gte:2}}},
{$group: {_id:"$_id.userId",event:{$push:"$_id.name"}}} ,
{$project:{size:{$size:"$event"}}},
{$match:{size:{$gte:2}}}
]).pretty();
预期输出-来自上述收集 {userId:1} 我只希望那些执行添加到购物车和项目查看事件(两者)超过2次的userId。
答案 0 :(得分:0)
这里是完整查询
db.Test.aggregate(
// Pipeline
[
{
$group: {
"_id": {
"userId": "$userId",
"name": "$name"
},
"count": {
"$sum": 1
}
}
},
{
$match: {
"count": {
"$gte": 2
}
}
},
{
$group: {
"_id": "$_id.userId",
"event": {
"$push": "$_id.name"
}
}
},
{
$project: {
"size": {
"$size": "$event"
}
}
},
{
$match: {
"size": {
"$gte": 2
}
}
},
]
);
您将在_id字段中获得您的userId。