MongoDB>;从嵌套数组中提取集合
我一直在尝试我找到的每一种方法,但都没有成功。尝试 在MongoDB中完成看似简单的任务(例如使用json/lodash非常简单) 我有一个收藏: db.users>MongoDB>;从嵌套数组中提取集合,mongodb,meteor,mongodb-query,aggregation-framework,Mongodb,Meteor,Mongodb Query,Aggregation Framework,我一直在尝试我找到的每一种方法,但都没有成功。尝试 在MongoDB中完成看似简单的任务(例如使用json/lodash非常简单) 我有一个收藏: db.users> [ { _id: 'userid', profile: { username: 'abc', tests: [ { _id: 'testid',
[
{
_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'] }
}
}
}
没有变化给了我我想要的,我确信我遗漏了一个核心概念,我查阅了文档,无法找到它。。我要找的基本上是一个平面图,可以提取出所有用户的所有问题,并按类型对它们进行分组
如果有人能把我引向正确的方向,我将不胜感激:)谢谢。(另外,我正在使用Meteor,因此任何查询都必须在Meteor mongo中工作)您可以在3.4中的聚合下面进行尝试
$filter
使用$map
筛选数学
类别,在每个匹配类别中投影问题
数组,然后是$reduce
和$concatarray
以将所有问题
放入所有匹配类别的单个数组
$REWIND
问题数组和$group
通过键入和$sum
计算正确的和错误的计数
db.users.aggregate([
{
"$match": {
"profile.tests.meta.category": "math"
}
},
{
"$project": {
"questions": {
"$reduce": {
"input": {
"$map": {
"input": {
"$filter": {
"input": "$profile.tests",
"as": "testf",
"cond": {
"$eq": [
"$$testf.meta.category",
"math"
]
}
}
},
"as": "testm",
"in": "$$testm.questions"
}
},
"initialValue": [],
"in": {
"$concatArrays": [
"$$value",
"$$this"
]
}
}
}
}
},
{
"$unwind": "$questions"
},
{
"$group": {
"_id": "$questions.type",
"correct": {
"$sum": {
"$cond": [
{
"$eq": [
"$questions.correct",
true
]
},
1,
0
]
}
},
"wrong": {
"$sum": {
"$cond": [
{
"$eq": [
"$questions.correct",
false
]
},
1,
0
]
}
}
}
}
])
抱歉,只复制了相关字段,但这是一个错误,应该是meta>category>math,而不仅仅是category。。我会更新Q,Thxy你真的让我开心了。。感谢您抽出时间。我是MongoDB的新手,试图确切了解您所做的工作,我将深入研究$reduce(当然:),在测试时,这个查询似乎运行得非常快,您有任何进一步优化的建议吗?我知道应该创建索引,这与此相关吗?我被告知将所有问题摘录到他们自己的收藏中。。在这种情况下,你会建议这样做吗。。或者他们在哪里都很好?谢谢。只能对$match
阶段使用索引。因此,为profile.tests.meta.category
添加索引。在选择一个选项之前,您必须测试所有选项。我还将尝试将问题移至顶层,并将其与相关元数据一起放入自己的数组中,以将其与相关测试联系起来(本质上是复制一些数据)。您现在还可以为需要的问题添加$match
。将此选项与当前结构和移动到其自己集合中的选项进行比较。