0

Users insert links into Mongo Collection and I want to retrieve most popular ones based on how many times is particular link in the collection. For a static data like how many links are coming from Youtube you can do the following:

Meteor.users.find({ "site": "youtube" }).count()

but how to go about dynamic data, as an example such a links:

Meteor.users.find({ "url": "youtube.com/watch?v=u1z4vkPWkLQ" }).count()

EDIT:

How to display on the client? When I do the following, there is an Error in console saying Videos.aggregate in not a function.

Template.frontPage.helpers({
 mostDownloadedVideos: function() {
  return Videos.aggregate(
   [
    { $unwind : "$filename"},
    { $group : { _id : "$filename", number : { $sum : 1} } },
    { $sort : {number : -1} },
    { $limit : 3 }
   ]
  );
 }
});
mhlavacka
  • 691
  • 11
  • 25

2 Answers2

1

You can use aggregate function of mongo. In your case:

Meteor.users.aggregate([
    { $project : { popular : { $url : "$url" } } } ,
    { $group : { _id : {url:"$url"} , number : { $sum : 1 } } },
    { $sort : { "_id.number" : -1 } }
  ])

With this you can take the top result or show list based on popularity.

JavaGhost
  • 406
  • 4
  • 8
  • Thank you for an answer, can you check my edit, bc I have some problems with that. – mhlavacka Oct 05 '15 at 20:53
  • You can combine this with @KubaWyrobek's answer. I dint realize that Meteor does not exposes aggregate function. Remember, it is best to run aggregation on the server side for best performance. You can also use [this](http://stackoverflow.com/questions/18520567/average-aggregation-queries-in-meteor) for reference for implementing a custom method for aggregation. – JavaGhost Oct 06 '15 at 11:54
1

Aggregate function is not exposed in meteor by default. However you can access it with package: meteorhacks:aggregate

var metrics = new Mongo.Collection('metrics');
var pipeline = [
  {$group: {_id: null, resTime: {$sum: "$resTime"}}}
];
var result = metrics.aggregate(pipeline);

Source

Kuba Wyrobek
  • 5,273
  • 1
  • 24
  • 26