One of the really cool, well designed features in MongoDB is the aggregation framework. Basically it is the feature that brings MongoDB query language on par with SQL in feature richness. Most importantly, it fully supports sharding for scale-out and parallel processing. I've had a lot of fun with it.
Last night I accidentally came up with a fun exercise that you can solve with a nice aggregation framework pipeline. I'll present it as a challenge, feel free to suggest answers in comments. I'll share my answer next week.
Suppose you work in a flag factory, and you have received the following orders:
> db.flags.find().pretty() { "_id" : ObjectId("52a7189ecd4dd732cd060201"), "country" : "Finland", "colors" : [ { "color" : "blue", "fabric_units" : 2 }, { "color" : "white", "fabric_units" : 3 } ], "num_flags" : 3 } { "_id" : ObjectId("52a718bccd4dd732cd060202"), "country" : "Sweden", "colors" : [ { "color" : "blue", "fabric_units" : 2 }, { "color" : "yellow", "fabric_units" : 2 } ], "num_flags" : 1 } { "_id" : ObjectId("52a718c2cd4dd732cd060203"), "country" : "Finland", "colors" : [ { "color" : "blue", "fabric_units" : 2 }, { "color" : "white", "fabric_units" : 3 } ], "num_flags" : 1 } { "_id" : ObjectId("52a71923cd4dd732cd060204"), "country" : "Norway", "colors" : [ { "color" : "red", "fabric_units" : 3 }, { "color" : "blue", "fabric_units" : 2 }, { "color" : "white", "fabric_units" : 1 } ], "num_flags" : 2 } { "_id" : ObjectId("52a7195bcd4dd732cd060205"), "country" : "Åland", "colors" : [ { "color" : "blue", "fabric_units" : 3 }, { "color" : "red", "fabric_units" : 2 }, { "color" : "yellow", "fabric_units" : 1 } ], "num_flags" : 1 }
You need to order an appropriate amount of fabric, of each color, to produce the number of flags given in num_flags. What is the aggregation framework query that will tell you how much fabric, of each color, do you need?
- Log in to post comments
- 22384 views