1

could you please suggest how to get an average size of a document in a group via aggregation? I have the following query:

db.Collection.aggregate(
  [
    {
      $match: {
          date: {
            $gte: ISODate("2020-04-29 14:18:22.560Z"),
            $lt: ISODate("2021-04-30 14:18:22.560Z")
         }
       }
    },
    {
        $group: { _id: '$objectType', count:{ $sum:1 }, avgSize: { $avg: ??? } }
    }
  ]
)

Collection sample doc:

{
    "_id" : UUID("..."),
    "date" : ISODate("2020-04-29T14:18:22.560Z"),
    "objectType" : << string >>,    
    "previousState" : << pretty long json >>,
    "currentState" : << pretty long json >>
}

I suspect it should be something with Object.bsonsize, but can't get what exactly.

berliner
  • 1,887
  • 3
  • 15
  • 23
  • Could you post how your collection looks like, few sample documents? – ngShravil.py May 07 '20 at 14:39
  • @ngShravil.py I updated the post – berliner May 07 '20 at 14:47
  • 1
    Does this answer your question? [Mongo = get size of single document](https://stackoverflow.com/questions/22008822/mongo-get-size-of-single-document) There is no such operator in `aggregate` as of now, If you check the lastest answer by Ashh you can find there is one coming in upcoming version `4.4` ! – whoami - fakeFaceTrueSoul May 07 '20 at 16:14
  • Oh Sorry, I thought document is a field in your collection. – ngShravil.py May 07 '20 at 16:41
  • @whoami Actually it doesn't really answer my question - I know that I can get a size of a single document, and I know that in v 4.4 this operator will be added. But I need an average document (entry) size in aggregation and my version is 4.2.1 – berliner May 08 '20 at 07:36
  • @whoami I understand his answer, but can't apply it to the earlier version of mongo, which we use. Meaning it's not answering my question – berliner May 08 '20 at 07:44
  • I’m not getting your point ! There is no way to do it in mongodb aggregation framework with mongoDB versions below 4.4 (As 4.4 is up coming everyone has to wait) till then either you need to change your ask or needs to implement it in code !! If this is what you wanted to see then I can ask @Ashh to edit his answer to add these lines lol :) anyway it is what that answer says indirectly..!!! – whoami - fakeFaceTrueSoul May 08 '20 at 07:49

0 Answers0