skip to Main Content

I have data on a MongoDB collection stored in documents like these:

{
  "_id": "657c54befca2b6a2cdd935ba",
  "data": {
    "name": "Bob",
    "surname": "xxx",
    "age": "20",
  },
  "header": {
    "data": "1702646974156",
  }
  "_class": "Prova"
}
{
  "_id": "657c54befca2b6a2cdd935bb",
  "data": {
    "name": "Tom",
    "surname": "yyy",
    "age": "25",
  },
  "header": {
    "data": "1702646974156",
  }
  "_class": "Prova"
}

it is possible through query/aggregate to obtain the data already formatted in an array of objects

{
  "data": [
    {
      "member": {
          "name": "Bob",
          "surname": "xxx"
      }
    },
    {
      "member": {
          "name": "Tom",
          "surname": "xxx"
      }
    }
  ]
}

Best regards

2

Answers


  1. You can do this with an aggregation like so:

    db.collection.aggregate([
      {
        $set: {
          "dataX.member": "$data"
        }
      },
      {
        $unset: "dataX.member.age"
      },
      {
        $group: {
          _id: null,
          data: {
            $push: "$dataX"
          }
        }
      },
      {
        $project: {
          _id: 0
        }
      }
    ])
    

    See HERE for a working example.

    Login or Signup to reply.
  2. Easiest way :

    db.collection.aggregate([
      {
        $group: {
          _id: null,
          data: {
            $push: {
              "member": {
                "name": "$data.name",
                "surname": "$data.surname"
              }
            }
          }
        }
      },
      {
        $project: {
          _id: 0
        }
      }
    ])
    

    See it here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search