I've a usecase in which I'll get dynamic field names in an array. I need to pass those fields to the mongo db aggregation query to get the sum of that field values in a given month. I need to remove the timeStamp & deviceId fields in array.
let jsonObj = [
{ name: "heat", value: "HEAT" },
{ name: "humidity", value: "HUMIDITY" },
{ name: "deviceId", value: "DEVICEID" },
{ name: "timeStamp", value: "TIMESTAMP" }
];
let vList = [];
jsonObj.forEach(async data => {
if (!data.name.match(/time/g) || !data.name.match(/deviceId/g)) {
vList.push(data.name); //Should exclude timestamp & deviceId (case-insensitive)
}
});
let variableObj = [];
vList.forEach(async data => {
let k = "{" + '"$sum":"$' + data + '"}';
// console.log(k)
k = JSON.parse(k);
variableObj.push(data + ":" + k);
});
Then resultant array looks like the following.
[ 'heat:{"$sum":"$heat"}',
'humidity:{"$sum":"$humidity"}',
'timeStamp:{"$sum":"$timeStamp"}',
'deviceId:{"$sum":"$deviceId"}' ]
Am not getting how to remove the single quotes around each item and how to pass them to query.
My query is:
db.collection(templateId).aggregate([
{
$match: {
entryDayTime: {
$lt: new Date(lastDay),
$gte: new Date(firstDay)
}
}
},
{
$group: {
_id: "$deviceId",
Count: { $sum: 1 }
// Should pass those array elements here like,
//heat:{"$sum":"$heat"},
//humidity:{"$sum":"$humidity"}
}
},
{ $sort: { entryDayTime: -1 } }
]);