Skip to content

Instantly share code, notes, and snippets.

@wilhelm-murdoch
Created August 18, 2013 07:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilhelm-murdoch/6260469 to your computer and use it in GitHub Desktop.
Save wilhelm-murdoch/6260469 to your computer and use it in GitHub Desktop.
Testing MongoDB aggregation problem. Creates 10 posters and randomly assigns them to 100 posts. Aggregation query returns mapping of poster to latest post sorted by creation date in descending order.
from pymongo import MongoClient
import datetime
import bunch
from faker import Faker
from random import choice
client = MongoClient(host="localhost", port=27017)
faker = Faker()
posters = []
for _ in range(0, 10):
posters.append(faker.name())
for _ in range(0, 100):
post = {
'poster': choice(posters)
, 'text': faker.lorem()
, 'created_at': datetime.datetime.utcnow()
}
client.aggr.posts.insert(post)
if __name__ == '__main__':
pipelines = []
pipelines.append({ '$sort': { 'created_at': -1 } })
pipelines.append({ '$project': { 'poster': '$poster' } })
pipelines.append({ '$group': { '_id': '$poster', 'post_id': { '$first': '$_id' } } })
pipelines.append({ '$skip': 0 })
pipelines.append({ '$limit': 10 })
results = client.aggr.posts.aggregate(pipelines)
print results['result']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment