我的任务是写一个查询,要求我列出主题类型的名称和属于每种主题类型的主题的总no。在数据库中,有两种不同的主题类型是核心和选修课。
在这里,数据库中包含两个不同主题类型的2个示例数据:
db.Subject.insert(
{
"_id":ObjectId(),
"subject":{
"subCode":"CSCI203",
"subTitle":"Algorithm and Data Structures",
"credit":3,
"type":"Core",
"prerequisite": ["csci103"],
"assessments": [
{ "assessNum": 1,
"weight":10,
"assessType":"Assignment",
"description":"Assignment 1 - Mathematic Concepts and Algorithm Complexity" },
{ "assignNum": 2,
"weight":15,
"assessType":"Assignment",
"description":"Assignment 2 - Linear and Non-linear Data Structure" },
{ "assessNum": 3,
"weight":15,
"assessType":"Assignment",
"description":"Assignment 3 - Greedy Algorithm and Branch-and-Bound" },
{ "assessNum": 4,
"weight": 60,
"assessType":"Examination",
"description":"Closed-book Final Examination" }
],
"book": [
{ "ISBN":"13:978-0-13-231681-1",
"bookType":"textbook",
"bookTitle":"Introduction to the Design and Analysis of Algorithms",
"edition":3,
"yearPub":2012,
"publisher":"Pearson",
"author": [ "Levitin" ] },
{ "ISBN":"978-0-262-53305-8",
"bookType":"reference",
"bookTitle":"Introduction to Algorithms",
"edition":3,
"yearPub":2013,
"publisher":"The MIT Press",
"author": [ "Thomas H Cormen", "Charles E Leiserson", "Ronald L Riverst", "Clifford Stein" ] } ]
}
}
)
db.Subject.insert(
{
"_id":ObjectId(),
"subject":{
"subCode":"IACT201",
"subTitle":"Professional Practice and Ethics",
"credit":3,
"type":"Elective",
"assessments": [
{ "assessNum": 1,
"weight":35,
"assessType":"Assignment",
"description":"Assignment 1 - Ethical Dilemma Case Study" },
{ "assignNum": 2,
"weight":25,
"assessType":"Presentation",
"description":"Presentation of Case Study" },
{ "assessNum": 3,
"weight": 40,
"assessType":"Examination",
"description":"Closed-book Final Examination" }
]
}
}
)如何使用聚合创建一个查询,使我能够计算核心和选修科目的数量?我现在很迷茫,因为两者都属于主题类型。
下面是一个期望结果的例子:{“核心科目”:6“选修科目”:1}
发布于 2020-11-19 07:26:30
如果只有2种类型,则可以用一行来表示:
db.collection.aggregate([{$sortByCount: "$subject.type"}])据我所知,唯一的问题是你不能让这个案子变得麻木不仁。
发布于 2020-11-19 04:26:17
您可以使用组
db.collection.aggregate([
{
$match: {
$or: [
{
"subject.type": "Core"
},
{
"subject.type": "Elective"
}
]
}
},
{
$group: {
_id: "$subject.type",
count: {
$sum: 1
}
}
}
])Working 蒙戈游乐场
https://stackoverflow.com/questions/64905357
复制相似问题