2

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.

Newbie Dev
  • 69
  • 6

2 Answers2

2

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]
        }
      }
    }
  }
]
thammada.ts
  • 5,065
  • 2
  • 22
  • 33
0

If the given documents are not sub-documents, then below is the approach:

db.collection.find({
  type: {
    $eq: "physical store"
  }
},
{
  location: 1,
  status: 1
})

MongoPlayGround link for the above

If, they are the part of a field (means they are sub-documents), then below is the approach:

db.collection.aggregate([
  {
    $project: {
      stores: {
        $filter: {
          input: "$stores",
          as: "store",
          cond: {
            $eq: [
              "$$store.type",
              "physical store"
            ]
          }
        }
      }
    }
  },
  {
    $unwind: "$stores"
  },
  {
    $project: {
      location: "$stores.location",
      status: "$stores.status",
      _id: "$stores._id"
    }
  }
])

MongoPlayGround link for the above

ngShravil.py
  • 4,742
  • 3
  • 18
  • 30