在
Users
集合中,我们有一个数组字段events
,它存储不同类别的事件。这是一个包含 2 个字段的对象数组:event
、category
。
我们尝试在 MongoDB 中设置一个查询,根据两个条件获取用户列表:
events
至少有 1 个具有“分析”类别的事件events
,其最后一个具有“Analytics”类别的事件是“Views”。举个例子:
[{
_id: "123",
events:[{
category: "Payment"
event: "ok",
},
{
category: "Analytics"
event: "Views"
},
{
category: "Analytics"
event: "Clicks"
}]
},
{
_id: "456",
events:[{
category: "Payment"
event: "ok"
},
{
category: "Analytics"
event: "Clicks"
},
category: "Payment"
event: "failed"
}]
}]
结果应该是:
[{
_id: "123",
events:[{
category: "Payment"
event: "ok"
},
{
category: "Analytics"
event: "Views"
},
{
category: "Analytics"
event: "Clicks"
}]
}]
我们尝试基于聚合和分组的查询,但它不起作用:
db.users.aggregate([
{
$match: {
"users.events.category": "Analyics",
"users.events.event": "Views"
}
},
{
$group: {
_id: "$_id",
shipment: { $first: "$$ROOT" }
}
},
{
$replaceRoot: { newRoot: "$shipment" }
}
])
您知道如何解决我们的问题吗?
我想你想要这样的东西:
db.users.aggregate([
{
$match: {
$and: [
{
"events.category": "Analytics"
},
{
$expr: {
$eq: [
{
$last: "$events.event"
},
"Views"
]
}
}
]
}
}
])