MongoDB Aggregation Framework fun: the answer

hingo's picture

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!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
MongoDB Aggregation Framework fun: ordering fabric for flags's picture

Pingback

[...] The answer has now been posted here. » hingo's blog [...]

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Use [fn]...[/fn] (or <fn>...</fn>) to insert automatically numbered footnotes.
  • Allowed HTML tags: <h1> <h2> <h3> <h4> <p> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <sup> <div> <blockquote> <pre> <img>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically. (Better URL filter.)

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
8 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.