Search code examples
mongodbmongodb-queryaggregation-frameworkpymongo

MongoDB: Get keys and values as separate arrays with new keys


I have the following MongoDB collection.

{
    "timestamp": "10:05:12",
    "value": 100
},
{
    "timestamp": "15:07:01",
    "value": 120
}, ... 

Note: Here "..." implies more data with the same structure.

Expected Result

{
    "timestamps" : ["10:05:12", "15:07:01", ...],
    "values": [100, 120, ...]
}

Solution

    1. $group - Group by null and with $push to add timestamp and value into timestamps and values arrays respectively.
    db.collection.aggregate([
      {
        $group: {
          _id: null,
          timestamps: {
            $push: "$timestamp"
          },
          values: {
            $push: "$value"
          }
        }
      },
      {
        $project: {
          _id: 0
        }
      }
    ])
    

    Sample Mongo Playground