Search code examples
jsonmongodbnosqlaggregation

How can I write a MongoDB query to return an array of arrays


Suppose that I have the following data in a collection called "users":

[
  {
    "_id": 1,
    "name": "Bob",
    "age": 22
  },
  {
    "_id": 2,
    "name": "Anna",
    "age": 30
  },
  {
    "_id": 3,
    "name": "John",
    "age": 30
  },
  {
    "_id": 4,
    "name": "Maria",
    "age": 22
  }
]

I want to write a query "grouping" the users by the age, so it will return an array of array. Something like this:

[
  [
    {
      "_id": 1,
      "name": "Bob",
      "class": 2
    },
    {
      "_id": 2,
      "name": "Anna",
      "class": 2
    }
  ],
  [
    {
      "_id": 3,
      "name": "John",
      "class": 5
    },
    {
      "_id": 4,
      "name": "Maria",
      "class": 5
    }
  ]
]

I've tried to write the query using aggregation, but the name is not an accumulator object, so it will never work.

db.users.aggregate([{"$group": {_id:"$age", _name:"$name"}}])

I've also read some stack overflow questions but I can't figure out how to solve my issue.


Solution

  • Maybe something like this:

    db.collection.aggregate([
     {
    "$group": {
      "_id": "$age",
      "field": {
        "$push": "$$ROOT"
      }
     }
    },
    {
    "$group": {
      "_id": "test",
      "theFinalArray": {
        "$push": "$field"
        }
       }
     }
    ])
    

    Explained:

    1. Group all documents by $age pushing the docs in array field
    2. Group all documents in another array with all field arrays inside

    Playground