Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregating on a ReferenceField in Mongoengine

In my app, I have a model for tracking site activity:

class FeedItem(Document):
    user = ReferenceField('User')
    link = ReferenceField('Link')
    issue = ReferenceField('Threat')
    action = StringField(required=True, max_length=1000)
    datetime = DateTimeField(required=True)

... where I keep track of what users do to content.

I am trying to create a "top users" list, where I aggregate a list of users by those who have made the most contributions (as determined, at least initially, by the number of times they show up in the log).

I tried this:

user_freqs = FeedItem.objects.item_frequencies('user', normalize=True)
top_users = sorted(user_freqs.items(), key=itemgetter(1), reverse=True)[:10]

(based on this example)

But I realized that that doesn't work because item_frequencies() doesn't work on ReferenceFields.

I am new at this, and am at a bit of a loss. Any help would be greatly appreciated. Thanks!

like image 890
nickgrossman Avatar asked Apr 23 '26 14:04

nickgrossman


1 Answers

I would recommend using raw pymongo and the aggregation framework, its a simple group by on FeedItem.user and $sum.

like image 54
Ross Avatar answered Apr 26 '26 05:04

Ross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!