pferrel
pferrel

Reputation: 5702

Find average event counts

I have a collection of events, so db.events contains many:

{
    "_id" : ObjectId("5e56c7d0c0c979b198cbe21a"),
    "event" : "buy",
    "userId" : "u1",
    "itemId" : "iPhone 12",
}

The collection is large and contains several types of events so I need to use the aggregation framework. I need to calculate:

To be clear my question is how to take an average of the resulting counts. I need a collection of essentially userId: [itemId1, itemId2, ...] containing every userId from buy events and itemId's grouped by the usereId. I want to average the count of unique itemId's over all userId's.

Upvotes: 1

Views: 45

Answers (1)

Valijon
Valijon

Reputation: 13103

Try this one:

db.events.aggregate([
  {
    $match: {
      event: "buy"
    }
  },
  {
    $group: {
      _id: "$userId",
      set: {
        $addToSet: "$itemId"
      }
    }
  },
  {
    $group: {
      _id: null,
      unique: {
        $sum: {
          $size: "$set"
        }
      },
      n: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0,
      avg: {
        $divide: [
          "$unique",
          "$n"
        ]
      }
    }
  }
])

MongoPlayground

Upvotes: 1

Related Questions