【发布时间】:2018-03-14 04:41:51
【问题描述】:
我有 3 个集合作业、状态、受让人。
分配字段:[_id、状态、受让人]
Assignee 和 Status 字段:[_id, name ]。
可以有许多分配与各种 Status 和 Assignee 集合相关联(通过 _id 字段链接),没有嵌套或复杂的数据。
我需要查询所有分配 ids 其中 Assignees 是行,Status 是列,组合单元格是 count,末尾有 Total 个计数。
为了帮助您形象化,我附上了下面的图片。我是复杂的Mongo DB Aggregate框架的新手,请指导我实现查询。
注意:Status和Assignee集合中的数据将是动态的。查询中没有预先确定任何内容。所以,行和列将来会动态增长,如果给查询分页,那将有很大的帮助。我不能用硬编码的
status名称编写查询,例如'pending'、'completed'等。随着数据的增长和现有数据可能会发生变化,例如'pending task'、'completed work'。
下面是我的查询
db.getCollection('Assignments').aggregate([
{
"$group": {
"_id": {
"assignee": "$assignee",
"statusId": "$statusId"
},
"statusCount": { "$sum": 1 }
}
},
{
"$group": {
"_id": "$_id.assignee",
"statuses": {
"$push": {
"statusId": "$_id.statusId",
"count": "$statusCount"
},
},
"count": { "$sum": "$statusCount" }
}
},
]);
以下是输出格式:
{
"_id" : "John",
"statuses" : {
"statusId" : "Pending",
"count" : 3.0
},
"count" : 3.0
}
{
"_id" : "Katrina",
"statuses" : [{
"statusId" : "Pending",
"count" : 1.0
},
{
"statusId" : "Completed",
"count" : 1.0
},
{
"statusId" : "Assigned",
"count" : 1.0
}],
"count" : 3.0
}
{
"_id" : "Collins",
"statuses" : {
"statusId" : "Pending",
"count" : 4.0
},
"count" : 4.0
}
预期输出为:
{
"_id" : "Katrina",
"Pending" : 1.0,
"Completed" : 1.0,
"Assigned" : 1.0,
"totalCount" : 3.0
}
关于如何将许多不同的statusId 用于不同的assignee 作为键而不是单个文档中的值的任何想法。
【问题讨论】:
标签: mongodb aggregation-framework