Following the examples I have two types of data in the same time series
db.weather.insertMany( [
{
"metadata": { "sensorId": 5578, "type": "temperature" },
"timestamp": ISODate("2021-05-18T00:00:00.000Z"),
"temp": 72
},//....
and..
db.weather.insertMany([
{
"metadata": {"sensorId": 5578, "type": "humidity" },
"timestamp": ISODate("2021-05018T00:00:001Z"),
"humpercent": 78
},//...
and I want to be able to serve simple requests by aggregating the data as:
{
sensorId: 5578,
humidityData: [78, 77, 75 ...],
tempData: [72, 72, 71...]
}
which seems like the obvious use case, but the
db.foo.aggregate([{$group: {_id: "$sensorId"}}])
function on sensorId
only returns the ids with no other fields. am i missing a simple identity aggregation function or a way to collect into an array?
2
Answers
If all you have is two categories, you can simply
$push
them:See how it works on the playground example – small
But if you want the generic solution for multiple measurements you need something like:
See how it works on the playground example – generic
What you are looking for is the $addToSet Operator:
Note that the order of elements in the returned array is not specified.