I have some data coming from an IoT device and i am storing that in the mongodb using the following structure:
{
data:{
<timeStamp1>:<energyValue1>,
<timeStamp2>:<energyValue2>,
<timeStamp3>:<energyValue3>,...
}
}
For example:
{
"data":{
"1648310504":51,
"1648310404":25,
"1648310304":63
}
}
Is there a way to unwrap this document into multiple documents in the aggregation pipeline so that the output in that stage will look something like this
Document 1. { "timestamp":1648310504, "data":51 }
Document 2. { "timestamp":1648310404, "data":25 }
Document 3. { "timestamp":1648310304, "data":63 }
CodePudding user response:
Maybe something like this:
db.collection.aggregate([
{
"$addFields": {
"data": {
"$objectToArray": "$data"
}
}
},
{
$unwind: "$data"
},
{
$project: {
timestamp: "$data.k",
data: "$data.v",
_id: 0
}
}
])
Explained:
- Convert the object data to array with elements key->k , value->v
- Unwind the array data so it disasemble to individual documents.
- Project the data sub-fileds as expected to timestamp & data.