我正在寻找关于如何在MongoDB中最好地处理这种类型的查询的一些指导.
我有一个购买数据库,每个都有一个课程属性以及购买者的日期.
我想要的是在有人购买初始产品后发生的购买清单.
所以 – 这里有一些pesudo查询:
// first find everyone who signed up for course A
{ course: 'a' }
然后
/*
out of those people, filter for those who in the future signed up
for another course
*/
{
course: { $in: ['b','c','d']},
date: { $gt: $courseA.purchaseDate }
}
这可能是聚合吗?或者我是否会为每次初次购买进行多次DB调用以检查是否有未来?
以下是每次购买数据的一些示例:
{ email: 'wes@example.com', course: 'a', purchaseDate: 10 },
{ email: 'wes@example.com', course: 'b', purchaseDate: 20 }, // match
{ email: 'wes@example.com', course: 'c', purchaseDate: 5 }, // not
{ email: 'nancy@example.com', course: 'a', purchaseDate: 5 },
{ email: 'nancy@example.com', course: 'c', purchaseDate: 6 }, // match
{ email: 'nancy@example.com', course: 'b', purchaseDate: 10 }, // match
{ email: 'nancy@example.com', course: 'd', purchaseDate: 1 }, // not
最佳答案 在Twitter上找到了一些帮助,找到了答案
.aggregate([
// Project the target purchasedate
{ $match: { course: { $in: ['JS3', 'RDX', 'WTF', 'RFB', 'ES6']}}},
{ $project: {
email: 1, amount: 1, course: 1, purchaseDate: 1,
target: {
$cond: {
if: { $eq: ['$course', 'JS3'] },
then: "$purchaseDate",
else: 0,
}
}
}},
// Group records by email, storing the target and the highest encountered purchase date
{ $group: {
_id: '$email',
courses: { $push: '$course'},
amounts: { $push: '$amount'},
count: { $sum: 1 },
spent: { $sum: '$amount' },
target: { $first: '$target'},
max: { $max: '$purchaseDate'}
}},
// // Check if the highest encountered date is greater then the target
{ $project: {
email: 1, course: 1, amounts: 1, spent: 1, count: 1, courses: 1, target:1, max: 1,
selected: { $cond: [{ $gt: ['$max', '$target']}, true, false] }
}},
// Filter out the non-matches
{ $match: {
target: { $gt: 0 },
selected: true,
spent: { $gt: 0 },
}},
{ $sort: { spent: -1 }}
])