Last week I posted a challenge about ordering fabric for a bunch of different flags, which can be conveniently solved with the MongoDB aggregation framework. Did you figure out the answer?
So we have a bunch of these flag orders for different countries:
{ "_id" : ObjectId("52a71923cd4dd732cd060204"), "country" : "Norway", "colors" : [ { "color" : "red", "fabric_units" : 3 }, { "color" : "blue", "fabric_units" : 2 }, { "color" : "white", "fabric_units" : 1 } ], "num_flags" : 2 }
And to calculate how much fabric we need of each color:
> db.flags.aggregate( [ { $unwind : "$colors" }, { $group : { _id : "$colors.color", fabric_units : { $sum : { $multiply : [ "$colors.fabric_units", "$num_flags" ] } } } } ] ) { "result" : [ { "_id" : "red", "fabric_units" : 8 }, { "_id" : "yellow", "fabric_units" : 3 }, { "_id" : "white", "fabric_units" : 14 }, { "_id" : "blue", "fabric_units" : 17 } ], "ok" : 1 }
Elegant, isn't it? As no RDBMS supports nested structures like these, and no NoSQL database really has similar aggregation functionality (that I know of), this is really cool and unique stuff you can do!
In the meantime, my collague John Page has posted a few lines of JavaScript to generate a Mandelbrot fractal with the MongoDB aggregation framework. (He also won the title of our team's biggest geek for 2013.) I suppose that is to say Merry Christmas to all you MongoDB hipsters out there, and see you next year!
- Log in to post comments
- 18663 views