Search code examples
mongodbnosql-aggregation

How to create an array containing arrays on MongoDB


I'm trying to make a query to mongodb. I want to get an array containing [location, status] of every document. This is how my collection looks like

{
"_id": 1,
  "status": "OPEN",
  "location": "Costa Rica",
  "type": "virtual store"
},
{
  "_id": 2,
  "status": "CLOSED",
  "location": "El Salvador"
  "type": "virtual store"
},
{
  "_id": 3,
  "status": "OPEN",
  "location": "Mexico",
  "type": "physical store"
},
{
  "_id": 4,
  "status": "CLOSED",
  "location": "Nicaragua",
"type": "physical store"
}

I made a query, using the aggregate framework, trying to get all documents that match that specific type of store.

{
 {'$match': {
   'type': { '$eq': "physical store"}
 }
}

What I want is something like this:

{
  {
  'stores': [
    ["Mexico", "OPEN"],
    ["Nicaragua", "CLOSED"]
   ]
 },
}

I tried with the $push but couldn't make it. Could someone please guide me on how to do it.


Solution

  • Since { $push: ["$location", "$status"] } would give you the error The $push accumulator is a unary operator. You would have to work around it a bit by passing to it a single object that output your desired array. One way to do it would be:

    [
      {
        "$match": {
          "type": {
            "$eq": "physical store"
          }
        }
      },
      {
        "$group": {
          "_id": null,
          "stores": {
            "$push": {
              "$slice": [["$location", "$status"], 2]
            }
          }
        }
      }
    ]