你能帮我吗?我有这些文件:
{
userId: 123,
event: 'A',
properties: {
status: 'Sent'
}
}
{
userId: 123,
event: 'B',
properties: {
status: 'Opened'
}
}
{
userId: 123,
event: 'C',
properties: {
status: 'Clicked'
}
}
我需要一个查询来匹配所有userId == 'A'
,它也注册了事件"B",但没有用properties.status == "Clicked"
完成事件"C"。
以下是我迄今为止所做的:
db.collection.aggregate([
{ $match: { "event": "A"} },
{
$lookup: {
from: "collection",
let: { "userId": "$userId" },
pipeline: [{
$match: {
$expr: { $eq: ["$userId", "$$userId"] }
}
}],
as: "events"
}
}
这给了我一个统一的输出:
{
userId: 123,
event: "A",
properties: {
status: 'Sent'
},
events: [
{ event: 'A' /* and all the other fields from original document */ },
{ event: 'B' /* and all the other fields from original document */ },
{
event: 'C',
properties: {
status: 'Clicked'
}
},
]
我下一步尝试这样做,但没有成功:
{
$match: {
$expr: {
$not: {
$and: [
{ $eq: ["$events.event", "C"] },
{ $eq: ["$events.properties.status', 'Clicked'] }
]
}
}
}
}
我的期望是,在这种情况下,这个查询不会给我带来userId: 123
,但它取决于结果。
有人能帮我吗?Tks!
我最终在查找后添加了这些步骤。不确定这是否是最好的解决方案,但我尝试过的任何其他方法都无法实现。
{ $unwind: "$events"},
{
$project: {
"userId": 1, "events": "$events",
"exclude": {
$cond: { if: {
$and: [
{ $eq: ["$events.event", "C"] },
{ $eq: ['$events.properties.status', 'Clicked'] }
]
}, then: 1, else: 0 }
}
}
},
{
$group: {
_id: "$userId",
exclude: { $sum: "$exclude" }
}
},
{
$match: { "exclude": 0 }
}