Home > Blockchain >  How to unwrap a mongodb nested document with unknown field names
How to unwrap a mongodb nested document with unknown field names

Time:03-27

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:

  1. Convert the object data to array with elements key->k , value->v
  2. Unwind the array data so it disasemble to individual documents.
  3. Project the data sub-fileds as expected to timestamp & data.

playground

  • Related