0

I need to unwind my prescriptions so I can get the total count per prescription

Here is one of my inserts

{
    "_id" : 1,
    "patient" : {
        "name" : "Locke, John",
        "id": 1,
        "sex": "male",
        "age": 52
    },
    "doctor": {
        "name" : "Grey, Meredith",
        "id": 12,
        "specialty": "general",
        "age": 42
    },
    "hospital": {
        "name" : "Seattle Grace",
        "id": 4,
        "location": {
            "street": "5th avenue",
            "city": "Taguig",
            "region": "Metro Manila",
            "zip code": 1634
            }
    },
    "date": {
        "month": 12,
        "date": 12,
        "year": 2019
    },
    "emergency_type": "non-emergent",
    "emergency_case": "severe headache",
    "waiting_time": 5123,
    "treatment": {
        "id": 1,
        "prescription": ["biogesic", "bed rest"]
    }

and here is the unwind code I have been trying to work around but I just can't get it to work.

 db.healthcare.aggregate([
  {
    $unwind: { path: "$prescription"}
  },
  {
    "$group": {
    "_id": "$treatment.prescription",
    "total prescriptions": { "$sum": 1 }
    }
  }

1 Answers1

1

You $unwind path is incorrect, it should be $treatment.prescription

db.healthcare.aggregate([
  {
    $unwind: {
      path: "$treatment.prescription"
    }
  },
  {
    "$group": {
      "_id": "$treatment.prescription",
      "total prescriptions": {
        "$sum": 1
      }
    }
  },
  {
    $sort: {
      "total prescriptions": -1
    }
  },
  {
    "$limit": 3
  }
])
Ayoub
  • 1,417
  • 14
  • 24