我是MEAN堆栈的新手。从我的一个API我设法得到以下JSON作为输出。
GET方法:
router.get('/', function (req, res, next) {
var decoded = jwt.decode(req.query.token);
User.findById(decoded.user._id, function (err, user) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
Treatment.find().sort('_id').limit(3)
.exec(function (err, treatments) {
if (err) {
return res.status(500).json({
title: 'An error occurred!',
error: err
});
}
res.status(200).json({
message: 'Success',
obj: treatments
});
});
});
});
JSON:
{
"message": "Success",
"obj": [
{
"_id": "5a3407b5b49aa6268419755f",
"patient": "5a3393ff963e821dc0f66598",
"t_date": "2017-12-15T17:30:45.365Z",
"symptoms": "fever,joint pain,headache,rash",
"signs": "changing levels of estrogen,dryness,nail breaks",
"review": ""
},
{
"_id": "5a3407cab49aa62684197562",
"patient": "5a3393ff963e821dc0f66598",
"t_date": "2017-12-15T17:35:45.365Z",
"symptoms": "fever,headache",
"signs": "nail breaks",
"review": ""
}
]
}
问题:我需要计算在给定的日期范围内出现症状的次数,例如我附上here的表格。我如何计算出现次数? (症状字段类型是mongoDB中的字符串,症状可能会有所不同)
编辑我在客户端没有任何列表/下拉列表。它只是一个文本框。
最后我能够从以下查询中做到这一点。我认为这将有助于像我一样遇到同样问题的其他人。
mongoDB查询
db.treatments.aggregate([
{ $match: { t_date: { $lt: new Date() } } },
{ $project: { sym: { $split:["$symptoms",","] }}},
{ $unwind: "$sym"},
{ $group: { _id: {"symtomp" : "$sym"}, count:{ $sum:1 } } }
])
示例mongoDB结果
{ "_id" : { "symtomp" : "rash" }, "count" : 1 }
{ "_id" : { "symtomp" : "headache" }, "count" : 2 }
{ "_id" : { "symtomp" : "joint pain" }, "count" : 1 }
{ "_id" : { "symtomp" : "fever" }, "count" : 2 }
您需要将症状字段作为字符串数组才能轻松完成。然后,Mongodb允许在“症状”字段列表中搜索包含特定值的所有文档。
EG
db.Treatment.find({"symptoms": "headache"}).count()