操作MongoDB响应NodeJS



我为mongodb做了一个"小"查询,以连接两个集合并检索数据。

游戏:在URL上插入2或3个参数

-include 可以是 0,1 或 2。

0 独家 1 个(含 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;
})

最新更新