[英]Grouping and counting Operations in MongoDB
I have two collections,which look like as follows我有两个集合,如下所示
Ticket_master票务大师
{
"_id" : ObjectId("5e70ed53de0f7507d4da8dc2"),
"TICKET_NO" : 1000,
"DESCRIPTION" : "<p>dsdsd</p>",
"ASSIGNED_TO" : ObjectId("5e78f2b2c0e09128e81db475"),
"RESOLVED_BY" : ObjectId("5e6f1c5b8451307f782d0992")
}
/* 2 */
{
"_id" : ObjectId("5e70f19c47df9479502f7933"),
"TICKET_NO" : 1001,
"DESCRIPTION" : "<p>vcvcv</p>",
"ASSIGNED_TO" : ObjectId("5e706e914587054254c02085"),
"RESOLVED_BY" : ObjectId("5e6f1c5b8451307f782d0992")
}
/* 3 */
{
"_id" : ObjectId("5e70f4fa47df9479502f7937"),
"TICKET_NO" : 1002,
"DESCRIPTION" : "<p>xcxc</p>",
"ASSIGNED_TO" : ObjectId("5e706e914587054254c02085"),
"RESOLVED_BY" : ObjectId("5e706e914587054254c02085")
}
Agent_master Agent_master
{
"_id" : ObjectId("5e6f1c5b8451307f782d0992"),
"NAME" : "A1",
}
/* 2 */
{
"_id" : ObjectId("5e706e914587054254c02085"),
"NAME" : "A2",
}
/* 3 */
{
"_id" : ObjectId("5e78f2b2c0e09128e81db475"),
"NAME" : "A3",
}
I need to perform various database operation like grouping and counting for getting the expected result,which is mentioned below我需要执行各种数据库操作,如分组和计数以获得预期结果,如下所述
Expected Output :预期输出:
[
{
NAME : 'A1',
COUNT:2,
},
{
NAME : 'A2',
COUNT:1,
},
{
NAME : 'A3',
COUNT:0,
}
]
I want to find the number of tickets resolved by each agents with name of the agents.我想用代理的名字找到每个代理解决的工单数量。
RESOLVED_BY
refers to the agent id who resolve the ticket. RESOLVED_BY
是指解决工单的代理 ID。
I hope you understand what I mean!我希望你明白我的意思! Thank you
谢谢
Tried with following Query :尝试使用以下查询:
db.getCollection('ticket_masters').aggregate([
{"$group" : {_id:"$RESOLVED_BY", count:{$sum:1}}}
])
Actual Output :实际输出:
/* 1 */
{
"_id" : ObjectId("5e78f2ddc0e09128e81db47a"),
"count" : 1.0
}
/* 2 */
{
"_id" : ObjectId("5e6f1c5b8451307f782d0992"),
"count" : 4.0
}
/* 3 */
{
"_id" : null,
"count" : 6.0
}
You can try below query :您可以尝试以下查询:
db.Ticket_master.aggregate([
/** Get agents info who resolved tickets */
{
$lookup: {
from: "Agent_master",
localField: "RESOLVED_BY",
foreignField: "_id",
as: "agent_docs"
}
},
/** As agent_docs is an array unwind into make it into objects */
{
$unwind: "$agent_docs"
},
/** Group on 'NAME' & count no.of occurrences of each NAME */
{
$group: {
_id: "$agent_docs.NAME",
COUNT: {
$sum: 1
}
}
},
/** Transform fields into required format */
{
$project: {
_id: 0,
NAME: "$_id",
COUNT: 1
}
}
])
Test : MongoDB-Playground测试: MongoDB-Playground
Here is answer这是答案
db.Agent_master.aggregate([
{
$lookup: {
"from": "Ticket_master",
"localField": "_id",
"foreignField": "RESOLVED_BY",
"as": "tickets"
}
},
{
$project: {
Name: '$Name',
Count: { $size: '$tickets'}
}
}
])
You have to use $lookup to jon two collections.您必须使用 $lookup 来连接两个集合。 Since you only need count so it can be done by $project only.
由于您只需要 count 所以它只能由 $project 完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.