Skip to content

Instantly share code, notes, and snippets.

@obj63mc
Created November 15, 2017 16:37
Show Gist options
  • Save obj63mc/f9f63c803b24685c47d304093302093d to your computer and use it in GitHub Desktop.
Save obj63mc/f9f63c803b24685c47d304093302093d to your computer and use it in GitHub Desktop.
Aggregating Votes on mongodb collection

#Schema

{
  _id:....
  votes:[...]
}

#Aggregation

db.posts.aggregate( [
  {$match: { "Votes.votedate": {$gte:thisMonth, $lt:thisMonthEnd} } },
  {$unwind: "$Votes" },
  {$match: { "Votes.votedate": {$gte:thisMonth, $lt:thisMonthEnd} } },
  {$group: { _id: "$title", votes: {$sum:1} } },
  {$sort: {"votes": -1} },
  {$limit: 10}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment