gpt4 book ai didi

MongoDB > 从嵌套数组中提取集合

转载 作者:可可西里 更新时间:2023-11-01 10:14:29 26 4
gpt4 key购买 nike

我一直在尝试在 SO 上找到的所有方法,但都没有成功。试在 MongoDB 中完成一个看似简单的任务(例如使用 json/lodash 非常容易)..

我有一个收藏:数据库用户 >

[
{
_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 中运行)

最佳答案

您可以在 3.4 中尝试以下聚合。

$filter 过滤 math 类别,使用 $mapquestions 数组投影到每个匹配类别中,后跟$reduce$concatArrays 将所有 questions 放入一个数组中,用于所有匹配类别。

$unwind 问题数组和$group 通过type$sum 来计算correct错误 计数。

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
]
}
}
}
}
])

关于MongoDB > 从嵌套数组中提取集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46403728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com