我尝试了SO上找到的所有方法,但都没有成功。在MongoDB中完成一个看似简单的任务(例如使用json / lodash非常容易)。
我有一个集合:
db.users >
[
{
_id: 'userid',
profile: {
username: 'abc',
tests: [
{
_id: 'testid',
meta: {
category: 'math',
date: '9/2/2017',
...
}
questions: [
{
type: 'add',
correct: true,
},
{
type: 'subtract',
correct: true,
},
{
type: 'add',
correct: false,
},
{
type: 'multiply',
correct: false,
},
]
},
...
]
}
},
...
]
我希望最终得到一个按问题类型分组的数组:
[
{
type: 'add',
correct: 5,
wrong: 3,
},
{
type: 'subtract',
correct: 4,
wrong: 9
}
...
]
我尝试过不同的聚合方式,最后一个是:
db.users.aggregate([
{ $match: { 'profile.tests.meta.category': 'math' }},
{
$project: {
tests: {
$filter: {
input: "$profile.tests",
as: "test",
cond: { $eq: ['$$test.meta.category', 'math'] }
}
}
}
},
{
$project: {
question: "$tests.questions"
}
},
{ $unwind: "$questions"},
])
也尝试在管道末尾添加$group:
{
$group:
{
_id: '$questions.type',
res: {
$addToSet: { correct: {$eq:['$questions.chosenAnswer', '$questions.answers.correct'] }
}
}
}
没有任何变化能够给我我想要的东西,我肯定是缺少核心概念,我查看了文档但还是搞不清楚.. 基本上我正在寻找一个flatMap函数,用它来提取所有用户的所有问题并按类型分组。
如果有人能引导我朝正确的方向前进,我将非常感激 :) 谢谢。(另外,我正在使用Meteor,所以任何查询都必须在Meteor mongo中有效)