0

I am working on grouping the MongoDB documents and updating the sample in the below link

https://mongoplayground.net/p/c2s8KmavPBp

I am expecting the output to look like

[
  {
    "group" : "one",
      "details":[{
        "avgtime" : 9.359833333333333,
        "title": "Scence 1"
    },{
        "avgtime" : 9.359833333333333,
        "title": "Scence 2"
    },{
        "avgtime" : 9.359833333333333,
        "title": "Scence 3"
    }]
  },
  {
    "group" : "two",
      "details":[{
        "avgtime" : 9.359833333333333,
        "title": "Scence 1"
    }]
  }
  ]

How to rename the field _id to the group and merge the two elements containing title: scence 1 and display their average time

Note: Question and sample link updated

1 Answer 1

1

Query

  • group by both field, to do the calculation
  • group by the one field and use the calculated avgtime
  • group the specific(here 2 fields) first and then the more general, using the values from the specific

PlayMongo

aggregate(
[{"$group": 
   {"_id": {"group": "$group", "title": "$details.title"},
    "avgtime": 
      {"$avg": 
        {"$divide": [{"$subtract": ["$endTime", "$startTime"]}, 60000]}}}},
 {"$group": 
   {"_id": "$_id.group",
    "group": {"$first": "$_id.group"},
    "details": {"$push": {"title": "$_id.title", "avgtime": "$avgtime"}}}},
 {"$unset": ["_id"]}])
Sign up to request clarification or add additional context in comments.

1 Comment

It works !! thanks. Got $unset Unrecognized pipeline stage name but i resolved by using $project and achieved the expected result. thanks

Your Answer

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