Home > Net >  MongoDB: Get keys and values as separate arrays with new keys
MongoDB: Get keys and values as separate arrays with new keys

Time:05-22

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, ...]
}

CodePudding user response:

  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

  • Related