我对 mongodb 做了一个“小”查询来连接两个集合并检索数据。
游戏:在 URL 上插入 2 或 3 个参数
-include 可以是 0,1 或 2。
0 独家 1 含 2 返回全部
-netcode:是过滤数据的关键 -group:另一个可选键,与第一个参数“include”一起使用
-我的查询运行良好,以某种方式返回特定组中事件发生的次数。
-问题是什么?我无法使用 mongo db 的结果,我需要将其解析为 JSON。 我对JS不太擅长,所以我不知道该把它放在哪里。由于我在公司工作,一些代码已经完成。
我的输出是这样的:
{
"events": [
{
"_id": {
"group": "GFS-CAJEROS-INFINITUM-TELDAT-M1",
"event": "SNMP DOWN"
},
"incidencias": 1
},
{
"_id": {
"group": "GFS-CAJEROS-MPLS",
"event": "Proactive Interface Input Utilisation"
},
"incidencias": 1209
},
{
"_id": {
"group": "GFS-CAJEROS-MPLS",
"event": "Proactive Interface Output Utilisation"
},
"incidencias": 1209
},
{
"_id": {
"group": "GFS-CAJEROS-MPLS",
"event": "Proactive Interface Availability"
},
"incidencias": 2199
},
{
"_id": {
"group": "GFS-SUCURSALES-HIBRIDAS",
"event": "Proactive Interface Output Utilisation"
},
"incidencias": 10
},
但我希望它以 JSON 格式融合,如下所示:检查事件名称的下一个 int 值。
[
{
"group": "GFS-CAJEROS-MPLS",
"Proactive Interface Input Utilisation" : "1209",
"Proactive Interface Output Utilisation" : "1209",
"Proactive Interface Availability" : "2199",
},
{
"group": "GFS-SUCURSALES-HIBRIDAS",
"Proactive Interface Output Utilisation" : "10",
},
我正在使用 Nodejs 和 mongodb 模块,因为我不知道这个函数到底是如何工作的,我不知道如何管理响应,有更好的方法吗?想要获取json文件,使用另一个js来生成它?
这是我正在使用的代码,基本上是重要的部分:
var events = db.collection('events');
events.aggregate([
{ $match : { netcode : data.params.netcode } },
{
$lookup:
{
from: "nodes",
localField: "name",
foreignField: "name",
as: "event_joined"
}
},
{ $unwind: {path: "$event_joined"} },
{ $match : {"event_joined.group" :
{$in:
[
groups[0] ,
groups[1] ,
groups[2] ,
groups[3] ,
groups[4] ,
groups[5] ,
groups[6] ,
groups[7] ,
groups[8] ,
groups[9] ,
]
}
}
},
{ $group : { _id : {group:"$event_joined.group", event:"$event"}, incidencias: { $sum: 1} } },
])
.toArray( function(err, result) {
if (err) {
console.log(err);
} else if (result) {
data.response.events = result;
} else {
console.log("No result");
}
最佳答案
您应该向管道中添加另一个 $group {_id: "$_id.group", events: {$push : {name: "$_id.event", incidencias: "$incidencias"}}}
然后使用“Array.map”更改 JS 代码上的数据结构。
data.response.events = data.response.events.map(function (eve){
var obj = {
"group": eve.group
};
eve.events.forEach(function (e){
obj[e.name] = e.incidencias
})
return obj;
})
关于javascript - 操作 MongoDB 响应 NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43881090/