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.

1
  • Are these documents a part of a field? Could you post a MongoPlayground link? Commented Apr 30, 2020 at 17:37

2 Answers 2

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]
        }
      }
    }
  }
]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.