gpt4 book ai didi

node.js - 如何返回从 MongoDb 中的一个数组过滤出来的多个数组

转载 作者:太空宇宙 更新时间:2023-11-03 22:19:47 25 4
gpt4 key购买 nike

我在 MongoDb 数据库中有一些数据,并使用 NodeJS MongoDb native 驱动程序访问它。

user: {
_id: ****Example Id****
name: 'Foo bar',
examScores: [
{ subject: 'Geography', score: 80, teacher: 'Mr Foo', date: 'somedate'},
{ subject: 'History', score: 57, teacher: 'Mrs Bar', date: 'somedate'},
{ subject: 'Maths', score: 43, teacher: 'Mrs Fizz', date: 'somedate'},
{ subject: 'Geography', score: 43, teacher: 'Mr Buzz', date: 'somedate'},
{ subject: 'Geography', score: 78, teacher: 'Mr Foo', date: 'somedate'},
{ subject: 'History', score: 41, teacher: 'Mr Buzz', date: 'somedate'}
]
}

我想检索每个科目的前十名分数/考试。为了简洁起见,我没有在示例中包含超过十次的考试尝试。

类似于:

user: {
_id: ****Example Id****
name: 'Foo bar',
grades: [
{ subject: 'Geography', exams: [
{ score: 80, teacher: 'Mr Foo', date: 'somedate' },
{ score: 78, teacher: 'Mr Foo', date: 'somedate' },
{ score: 43, teacher: 'Mr Buzz', date: 'somedate' }
]
},
{ subject: 'History', exams: [
{ score: 57, teacher: 'Mrs Bar', date: 'somedate' },
{ score: 41, teacher: 'Mr Buzz', date: 'somedate'}
]
},
{ subject: 'Maths', exams: [
{ score: 43, teacher: 'Mrs Fizz', date: 'somedate'}
]
}
]
}

最佳答案

尝试这个查询希望它有帮助。我用过$unwind ,然后聚合数据。

db.collection.aggregate([ {$unwind:"$examScores"}, 

{$group:{"_id":"$examScores.subject",name: { $first: "$name" }, exams: {

$addToSet:{ teacher: '$examScores.teacher'

,score:'$examScores.score',date:'$examScores.date' } }}},

{$group:{"_id":null,name: { $first: "$name" }, "grades":{$push:

{"subject":"$_id", "exams":"$exams"}}}},

{$project:{"_id":0,"grades":1,"name":1}} ])

我得到的预期输出是在我的本地计算机上

{
"name": "Foo bar",
"grades": [
{
"subject": "History",
"exams": [
{
"teacher": "Mr Buzz",
"score": 41,
"date": "somedate"
},
{
"teacher": "Mrs Bar",
"score": 57,
"date": "somedate"
}
]
},
{
"subject": "Maths",
"exams": [
{
"teacher": "Mrs Fizz",
"score": 43,
"date": "somedate"
}
]
},
{
"subject": "Geography",
"exams": [
{
"teacher": "Mr Foo",
"score": 78,
"date": "somedate"
},
{
"teacher": "Mr Buzz",
"score": 43,
"date": "somedate"
},
{
"teacher": "Mr Foo",
"score": 80,
"date": "somedate"
}
]
}
]
}

关于node.js - 如何返回从 MongoDb 中的一个数组过滤出来的多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59018862/

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