Created
August 18, 2013 07:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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