Home > Software design >  How to return column instead of data row?
How to return column instead of data row?

Time:10-06

How to retrieve data by columns using node, mongodb, Any idea on how to do it ?

For now i'm retrieving data like this,

schema.method("toJSON", function () {
        const { _id, ...object } = this.toObject();
        object.id = _id;
        console.log('OBJECT ', object)
        return object;
    });

what i got right now is,

[
  {
    "username": "2",
    "heartrate": 150,
    "bodytemperature": 110,
    "bloodoxygen": 210,
    "bloodpressure": 240,
    "createdAt": "2021-10-02T18:11:09.559Z",
    "updatedAt": "2021-10-02T18:11:09.559Z",
    "__v": 0,
    "id": "6158a0bddd4ee2fd9dffaa6b"
  },
  {
    "username": "2",
    "heartrate": 150,
    "bodytemperature": 110,
    "bloodoxygen": 210,
    "bloodpressure": 240,
    "createdAt": "2021-10-02T20:00:20.173Z",
    "updatedAt": "2021-10-02T20:00:20.173Z",
    "__v": 0,
    "id": "6158ba54ba54444d2c69f0cc"
  }
]

what i want is this,

{
  "username":[ "2", "2"],
  "heartrate": [150, 150],
  "bodytemperature": [110, 110],
  "bloodoxygen": [210,210],
  "bloodpressure": [240, 240]
}
  

Thanks

CodePudding user response:

You can $group by null to get all objects together and $push into an array like this:

yourModel.aggregate([
  {
    "$group": {
      "_id": null,
      "username": {
        "$push": "$username"
      },
      "heartrate": {
        "$push": "$heartrate"
      },
      "bodytemperature": {
        "$push": "$bodytemperature"
      },
      "bloodoxygen": {
        "$push": "$bloodoxygen"
      },
      "bloodpressure": {
        "$push": "$bloodpressure"
      }
    }
  }
])

Example here

Also you can add an extra stage in aggregation pipeline to not output _id: null example here.

The result is:

[
  {
    "bloodoxygen": [210,210],
    "bloodpressure": [240,240],
    "bodytemperature": [110,110],
    "heartrate": [150,150],
    "username": ["2","2"]
  }
]
  • Related