我正在用mongoose在nodejs中构建Web API。我正在开发的功能的严格目标是检索数据以绘制有关它们的图表。IT应用程序本身从本地打印机中收集数据,并将数据列入API(每10分钟(。这些扫描中的每一个都会产生一个蒙戈文档,其中包含有关打印机所需的所有信息,当然,创建的字段是代表创建文档的日期和时间的同义字段。
我需要构建一个查询,该查询给定给出打印机标识符,并且一个时间段需要每天检索1个扫描(在下种情况下,因为它是每月变化(,为每个打印机标识符。第一个或最后一个是相同的。这是我的错误示例,因为我不确定如何进行此操作。
var codeList = [ webAppId1, webAppId2, webAppId3 ];
Printer.aggregate(
[{
$match: {
codiceSim: {
$in: codeList
},
Created: {
$gte: new Date(new Date().setDate(new Date().getDate() - 30))
}
}
}, {
$sort: {
Created: -1
}
}, {
$project: {
year: {
$year: "$Created"
},
month: {
$month: "$Created"
},
day: {
$dayOfMonth: "$Created"
},
$original_doc: "$$ROOT"
}
},
{
$group: {
_id: {
codiceSim: "$codiceSim",
year: "$year",
month: "$month",
day: "$day"
}
}
}
],
function (err, printers) {
if (err) res.send(err);
res.json(printers);
}).exec(function (printers) {
});
我希望的结果应该与此相似(为了清楚起见,以下是一周数据的结果,每天1 doc,3张打印机(
[
[{docScan1},{docScan2},{docScan3},{docScan4},{docScan5},{docScan6},{docScan7}], <= printer1
[{docScan1},{docScan2},{docScan3},{docScan4},{docScan5},{docScan6},{docScan7}], <= printer2
[{docScan1},{docScan2},{docScan3},{docScan4},{docScan5},{docScan6},{docScan7}] <= printer3
]
我已经有一个查询来收集与我期望的一台打印机相同的数据,这就是我的工作方式:
Printer.aggregate(
[{
$match: {
codiceSim: req.params.printerId,
Created: {
$gte: new Date(new Date().setDate(new Date().getDate() - 30))
}
}
},
{
$project: {
year: {
$year: "$Created"
},
month: {
$month: "$Created"
},
day: {
$dayOfMonth: "$Created"
},
original_doc: "$$ROOT"
}
},
{
$group: {
_id: {
year: "$year",
month: "$month",
day: "$day"
},
docs: {
$push: "$original_doc"
}
}
},
{
$replaceRoot: {
newRoot: {
$arrayElemAt: ["$docs", 0]
}
}
},
{
$sort: {
Created: -1
}
}
],
function(err, printers) {
if (err)
res.send(err);
res.json(printers);
});
需要在单个jQuery async呼叫中注入来自同一图表中不同打印机的某些数据,以尝试找到解决方案,但我很困惑。谢谢
到目前为止,我选择完整地绕过解决方案来完善我的猫鼬aggr查询,但我真的很期待在这个方向上提供一些帮助。
这是我做到的:
Printer.find({
codiceSim: {
$in: codeList
},
Created: {
$gte: new Date(new Date().setDate(new Date().getDate() - 30))
}
}).lean().exec(function (err, printers) {
if (err) res.send(err);
var partial = new Array(codeList.length);
var final = new Array(codeList.length);
var times = [];
for (var i = 0; i < 30; i++) {
times.push(new Date(new Date().setDate(new Date().getDate() - (30 - i))));
}
codeList.forEach(function (item, index, arr) {
partial[index] = printers.filter(printer => printer["codiceSim"] === item);
if (partial[index] != undefined) {
times.forEach(function (cDate) {
var tmp = partial[index].filter(function (item) {
if (cDate.getFullYear() === item["Created"].getFullYear() &&
cDate.getMonth() === item["Created"].getMonth() &&
cDate.getDate() === item["Created"].getDate()) {
return item;
}
});
if (tmp != undefined && tmp.length > 0) {
if (final[index] === undefined) {
final[index] = new Array();
}
final[index].push(tmp[0]);
}
});
}
});
res.json(final);
});