0

here is the collection and query code. Now i want to do two things.

i) sort reportTypes array objects by counts in descending order then,

ii) sort the collection by total no. of counts in reportTypes array in descending order.

iii) then group by managerId

i want resultant doc to like this.

[
  {
    "_id": ObjectId("62441917d12596f96de163a3"),
    "managerId": 2,
    "reportTypes": [
      {
        "reasonId": 100,
        "count": 20
      }
    ]
  },
  {
    "_id": ObjectId("62441917d12596f96de163a5"),
    "managerId": 3,
    "reportTypes": [
      {
        "reasonId": 200,
        "count": 10
      },
      {
        "reasonId": 100,
        "count": 5
      },
      {
        "reasonId": 300,
        "count": 0
      }
    ]
  },
  {
    "_id": ObjectId("62441917d12596f96de163a2"),
    "managerId": 1,
    "reportTypes": [
      {
        "reasonId": 300,
        "count": 4
      },
      {
        "reasonId": 200,
        "count": 3
      },
      {
        "reasonId": 100,
        "count": 2
      }
    ]
  }
]
3
  • can you add example document about how you expect the final document to look like? Commented Mar 31, 2022 at 19:24
  • yeah sure mongoplayground.net/p/wRL0YdS7eUb Commented Apr 1, 2022 at 4:49
  • order of collection is different and reportTypes object's order is also different. Collection is sorted in descending order of total no. of counts & reportTypes objects are also sorted in descending order of count. Commented Apr 1, 2022 at 7:31

1 Answer 1

1

Maybe something like this:

db.collection.aggregate([
{
  $unwind: "$reportTypes"
},
{
  $sort: {
   "managerId": 1,
   "reportTypes.count": -1
 }
},
{
 $group: {
  _id: "$managerId",
  reportTypes: {
    $push: "$reportTypes"
  },
  cnt: {
    $sum: "$reportTypes.count"
   }
 }
},
{
  $addFields: {
    managerId: "$_id"
 }
},
{
 $sort: {
   cnt: -1
}
},
{
  $project: {
    managerId: 1,
     reportTypes: 1
  }
 }
])

Explained:

  1. Unwind the reportTypes
  2. Sort by managerId and descending by reportTypes.count
  3. group with push to form the same objects with sorted arrays per managerId and generate summary count per managerId.
  4. addFileds managerId
  5. Sort by total count ( cnt)
  6. Project only the needed fields

playground

Sign up to request clarification or add additional context in comments.

6 Comments

thanks man for so much effort i can't ask more. But it is not what i am looking. I am really grateful to you.
Let me know what different is expected?
yeah, i have added in question's comment section
check the pg it is same resulting doc as expected: mongoplayground.net/p/LmzUHTDcL8m
add to the question
|

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.