如何在MongoDB中创建嵌套组?(How to make nested group in MongoDB?)

编程入门 行业动态 更新时间:2024-10-13 06:20:41
如何在MongoDB中创建嵌套组?(How to make nested group in MongoDB?) mongodb

假设Mongo中有数据! 有几个项目,还有管理者,分配问题的人。 每个问题都分配给不同的人,因为项目有不同的部分。 如何计算数字,每个受让人都已在项目中分配。 例如:

{ "Project A": { "Ted":10, "Matt":5 }, "Project B": { "Mary":3, "Hector":30 } }

以下内容写入总和,但不对其进行分组:

db.test.issues.group({ "key": { "project": true "assignee":true }, "initial": { "countassignee": 0 }, "reduce": function(obj, prev) { prev.countassignee++; } });

它将返回:

{ { "project": "Project A", "countassignee":10, "assignee":"Ted" } .... }

Assume there's a data in Mongo! There are a few projects, and there're managers, to who the problems are assigned. Each problem is assigned to different people as the project has different parts. How can one compute the number, each assignee has been assigned within a project. For example:

{ "Project A": { "Ted":10, "Matt":5 }, "Project B": { "Mary":3, "Hector":30 } }

The following writes the sum but doesn't group it:

db.test.issues.group({ "key": { "project": true "assignee":true }, "initial": { "countassignee": 0 }, "reduce": function(obj, prev) { prev.countassignee++; } });

It will return as:

{ { "project": "Project A", "countassignee":10, "assignee":"Ted" } .... }

最满意答案

您提供的数据样本非常令人困惑。 它的项目A和项目B应该是不同的文件。 我相信组的最佳用途是在集合中进行集合,如果你想在doucment中计算,你可以使用javascript。

OK! It doesn't seem like the best answer, but it'll do! first define a cursor sorting by projects

var cursor = db.test.find().sort({projects:1});

a list for the counter:

var asgn_nums = {};

and a variable holding project name;:

var project = '0';

Here counts for each project:

while (cursor.hasNext()) { var issue = cursor.next(); var p = issue.project; if(p != project) { if(project != '0'){ print(project+":"); printjson(asgn_nums); } project = p; asgn_nums = {}; } if(issue.assignee != null) { if (asgn_nums[issue.assignee] == null) asgn_nums[issue.assignee] = 1; else asgn_nums[issue.assignee]+= 1; } if(!cursor.hasNext()) { print(project+":"); printjson(asgn_nums); } }

更多推荐

本文发布于:2023-04-29 03:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334471.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   如何在   group   MongoDB   nested

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!