Tuesday, December 14, 2010

Using Underscore.js with MongoDB

I've been using MongoDB for a while now and have been really happy with it. I wanted to share something we are doing on of the projects I work on that makes working with Mongo even better.

MongoDB allows for the use of JavaScript to do lots of work on the server side. This includes running MapReduce jobs on collections, but also can be used in where clauses and for doing grouping. Being able to use JavaScript for these things is handy, but using just the core JavaScript language can be less than ideal. That's why we prime our MongoDB environment with Underscore.js.

On the Underscore website, it claims to be a JavaScript utility belt. I've found that to be the case. It has functions like any or include that save you the trouble of having to write for loops to iterate over arrays. While the MongoDB documentation describes how you can store individual functions for server side use, it didn't really touch on how you could load an entire library like Underscore.

It turns out you can load up libraries like this pretty easily using db.eval(). I recall reading (but can't currently find the docs to prove this) that every MongoDB connection has a JavaScript context associated with it. If you create functions in this context, they will exist as long as the connection is around. So if you just eval the Underscore.js library before you do any work with your connection, you will have access to all of its functions to do your work.

Here is an example of how to use Underscore.js with the Ruby driver. In this example, I'll set up the MongoDB connection with Underscore.js, create a sample dataset of cars, then use Underscore to group them by make without repeating model.




The only downside to this approach is that db.eval does not seem to work with sharding. That is OK for me right now, but YMMV. Also note that I am using the awesome_print gem to pretty print the results.

56 comments:

alfred said...
This comment has been removed by the author.
alfred said...

JavaScript is client-based, which means it does not have to make any server requests to run. This makes it ideal for fast response and initial validation of form input.

javascript jobs

Kevin Taylor said...

Actually nevermind. It seems when it prints it to the console it doesn't show the nested likes... Weird. But they are actually being sent to the view. Well that settles that. To see more info please visit http://essayswriters.org/college/ Thanks.

yakenzu toby said...

Thank you for for sharing so great thing to us. I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post nice post, thanks for sharing. ibcbet, judi bola, sbobet, agen bola, ibcbet, sbobet

steve7876 said...

From the plenty of feedback on your content, I think I am not the only one having all the enjoyment here! Keep up the great perform. I have been significance to create something like this on my web page and you have given me an concept.Buy Best wholesale kithen Towel

Selina Diana said...

To start with the foremost necessary line of my statement – I do yearn to provide Associate in Nursing outsized as a results of the periodical esteem. very it's pleasing laurels wondrous work by him that i detected out laurels dependable facilitate by his/her Brobdingnagian detail and figures instant payday loan. I merely have to be compelled to be compelled to be compelled to be compelled to be compelled to be compelled to be compelled to broadcast, Brobdingnagian delight comprise it up your work. usually I’ll sit down at the side of your posting and alter. esteem ahead to your a allotment of mails.

Jesmin Rayen said...

Regardless of the possibility that you have not made an expert piece since school, exposition composing programming will help you make a cleaned and expert report you'll be glad to impart to different people in your business. It will help you relearn the best possible rules, and also mentor you on new ones. Regardless of what you have as a main priority to your composition, get your incredible thoughts on papers in the right organization to wind up considered important. Get write my essay paper here.

Tome mark said...

Scholarly research papers are composed to help understudies take in more about the books they read. Exploration papers are intended to compel the understudy to peruse a novel discriminatingly and after that to expound on some point or contention of their picking. research paper service

Sang Pemikir said...

I am very happy to read this article, thanks for giving us go through info.Fantastic nice. I appreciate this post. Agen Bola

Zacky van Hardi said...

Really good read for me, This is exactly what I was looking for. Thanks for sharing this great article! That is very interesting Smile I love reading and I am always searching for informative information like this! Agen Sbobet

Samuel Moreland said...

Work misfortune does not kill the commitment to pay back a car title loans huntsville advance. On the off chance that you lose your employment and don't have another paycheck, the payday advance can be paid off utilizing a check, Visa or cash raised by offering resources.

MUSA77 said...

Vitality the affiliation gets commitment with respect to vehicle. The affiliation can either offer the vehicle or turn it over to accumulations. So are auto title credit affiliations a trap? Absolutely, NOT. The borrower basically must be watchful they could call their own particular individual records. auto title loans

marko said...

We comprehend that Tax Season is close, and you have likely as of now been chasing for your vehicle of decision. We at Lightning Fast Car Loans, encourage you to take as much time as required, and exploration the auto you might want to purchase, assess it altogether, to make sure that you'll be settling on a sound and fulfilling decision.Car Title Loans

ariyan arifin said...

I in like manner oblige you to understand that the evacuate it letter can be used for any sort of obligation aggregating and not just payday credits. It is major to know your rights and you can find them out online at the association trade commission's site page where you can get a couple answers concerning the sensible obligation get-together act. You will perceive what banks can and can't do concerning the amassing of your obligations and how to stop to a great degree shaped and annoying behavior. title loan

Digital Mission said...

This is an imperative issue to consider before taking out attributes that oblige you to set up your auto or truck as protection. Exactly when increased consistently, the interest rate and costs can incorporate quickly. Really, a couple advance authorities truly charge triple-digits in yearly leisure activity. www.usacheckcashingstore.com/san-diego

marko said...

If you wish to benefit a development at lower rates, then you can request 30 day advances no credit check. They help you handle your prior obligations without breaking a sweatcash advances montgomery

jhon romeo said...

Mastercards are a great part of the time used to pay for these sorts of crises, yet in the event that the accessible balance misses the mark, an individual will need to handle the budgetary smash in another way. Auto title advances have a tendency to be a savvy fix for those obliging quick cash. payday loans

marko said...

While looking for shabby auto advances may take a little time and imply that you won't conclude your credit instantly, it is unquestionably justified, despite all the trouble realizing that you can spare a considerable sum in enthusiasm over the term of your advance. Payday Loans

Facebook Descargar said...

Thank you for your post, I look for such article along time, today i find it finally. this post give me lots of advise it is very useful for me
Signature:
download descarga facebook gratis para Android celular and download free descargar facebook gratis and descargar facebook gratis , descarga facebook

Whatsapp Descargar said...

I was working and suddenly I visits your site frequently and recommended it to me to read also. The writing style is superior and the content is relevant. Thanks for the insight you provide the readers!
Signature:
download free descargar whatsapp and download baixar whatsapp online and descargar whatsapp gratis , baixar whatsapp gratis

Frozen Juegos said...

Very interesting! Thanks you.
Signature:
Jugar juegos de frozen en línea gratis, los nuevos de princesa de Disney juegos frozen - la princesa encantadora y linda. Divertirse frozen!

ariyan arifin said...

Along these lines, after a rationalism a man would ache for a bread-and-spread abetment to oversee the heft of an abettor bicycle and such abetment will be usual by change for abettor bicycle propels. Car Title Loans Chicago

marko said...

The advance business sector for bicycle money can likewise be gotten to through the web. It is feasible for 24 hours of applying for it. It offers low intrigue rates, wicked good installment, ideal reimbursement period, terms that are adaptable and simple portions consistently. payday loans

marko said...

By utilizing a gathering of your nearby companions or family, a gathering transport can be good to beat all the cake over your exceptional night. It can be numerous more energizing than you ever considered. It's the best for you to parade your thing and add to a point at the taxi end of your mates. check cashing costa-mesa

jhon romeo said...

A couple of associations will continue endeavoring and accumulate from you despite this so I have another proposition if this happens. If you get different social occasion yells toward you have taught them about your commitment blend you need to fax and/or send them a remove it letter. www.usacheckcashingstore.com/san-diego

MUSA77 said...

Title credits are named accordingly as a delayed consequence of the banks requesting the guaranteeing of commitment in regards to vehicle, known as the title. The borrowers are in like way not limited from making utilization of the vehicle amidst the season of the improvement, in light of the way that essentially title is held by the credit genius. Check Cashing

MUSA77 said...

The alignment of accepting aid through appellation credits is the aforementioned as alternating advances. Borrowers allegation be alert for accommodation specialists who allegation abundantly aerial ante of hobby. One allegation booty appellation credits aloof from the accustomed banks why should accustomed action these advances. Payday Loans San-diego

games unblocked said...

great post. i like it. feeling great when reading your post .
kid games
friv2
unblocked games 77
juego de un show mas

Mít Trang said...

great article, I was very impressed about it, wish you would have stayed next share
juegosjuegos
juegos de zombies
jogos de friv

Mission Vission said...

That surmises the borrower may have lost their work, can't stay to pay their rent, may oblige cash for their childhood's school enlightening cost; there could be different potential results why the borrower is in excursion for moment money. Subordinate upon the borrower's vehicle respect, the borrower can get up to whatever the most amazing the movement affiliation may offer. Payday Loans

sojib hossain said...

Particularly else, you have to understand where these on the web, Custom College Essay shaping affiliations get their works from. Regardless of the way that, most such affiliations will endeavor to actuate you that they are on an exceptionally fundamental level going on these papers through an expert and skilled get-together of scientists. Payday Loans San-diego

Shan Jonson said...

As added contempo authority builders would discover, the Roman Authority begin that colonization came at a cost, which ultimately negated the assets made. The legions of soldiers and admiral of every rank, which were bare to defended area and accumulate the colonized citizenry subjugated, all had to be paid.
auto title loans

Shan Jonson said...

Gold bill were a acceptable adjustment of acquittal but they did animate a banknote abridgement the like of which had not ahead been experienced. Bodies bought rather than grew or fabricated what they needed, and their needs broadcast as the money at their auctioning increased. Added gold was appropriate to accumulate clip with the demand.
https://www.usapaydayloanstore.com/chicago

jhon said...

Getting a fast claimed accommodation can be accessible and quick, abnormally if you apperceive absolutely area to go. At times like these, aback anybody is broadly afflicted by the all-around banking crisis, it is analytical that a actuality knows area to go to in case they charge a quick loan. It is awful important to go to the appropriate antecedent to additionally abstain instances of betray and actuality defrauded. Alive how to get accustomed for a quick accommodation will save you from activity added into bankruptcy.
https://www.usacheckcashingstore.com/costa-mesa

jhon said...

Fast claimed loans assignment analogously as any added accommodation applications, except for the speedier bulk of time complex in the processing. The borrower aboriginal needs to acquisition a payday accommodation boutique or any acclaimed or accurate aggregation that can annual loans online. You will be asked to accommodate specific claimed advice through a accommodation appliance form. These pieces of advice are capital in adjustment to actuate your adeptness to pay as able-bodied as how the claim arrangement will work.
usacheckcashingstore.com/corona

Hieu Nguyen said...

When you're tired, you want to relax after a stressful working hours, you need to have time to take care of the kids active.
Please visit our website and play exciting flash games.
Thanks you for sharing!
Friv 4

Justin said...

Much the same as the business advances, you likewise need to sign an agreement and make a calendar of your customary regularly scheduled installment together with the loan fee you two concurred. Check Cashing

Friv4 Games Online said...

great post. i like it. feeling great when reading your post. Keep on posting!
happy wheels | friv4school | happy wheels

Justin said...

A few universities may have programs where the credits can be supported specifically to the school once they're endorsed. If so, you should simply round out the printed material for the advance and the cash is sent straightforwardly to the predefined school. The assets are then connected towards your educational cost and you are ready the length of you have a positive equalization. check cashing carson

Justin said...

The essential prerequisites are that you are an American national. Another advantage to these kind of credits is that when you apply for government money related guide, you naturally get went into government stipend programs. Gifts can truly help you spare cash since they are free cash - you don't need to try attempting to reimburse them. This implies you wind up sparing a ton of cash over the long haul - something that can't be downplayed. Cash Advance Chula-vista

marko said...

Nel corso del tempo i computer, sono diventati più piccoli, più leggeri, operare più velocemente e avere prezzo significativamente calati di prezzo. Così molti di più di noi hanno incorporato i computer nella nostra vita quotidiana e nelle case. il colloquio di lavoro in inglese esempio

marko said...

La buona notizia è che ci sono alcuni buoni prodotti là fuori che utilizzano ingredienti a base di erbe di prima qualità in dosi forti. Gli ingredienti di questi prodotti sono rigorosamente testati per la forza e la purezza. Queste pillole possono essere acquistati con discrezione attraverso internet, ma bisogna trovare una fonte affidabile. pillola blu pagamento alla consegna

Justin said...

Understudies additionally have the alternative of applying for a new line of credit from a private loan specialist, for example, a bank. It is not important to present a FAFSA for one of these advances, yet you will need to apply through the private association and meet their guidelines to qualify. Payday Loans

Justin said...

With a governmentally supported school credit, some portion of your elected advance understudy rights is that if you pass away, your companion is not at risk for what you owe. Actually, your credit is consequently scratched off and the administration will release any outstanding obligation. Private credits are distinctive, however. check cashing

Justin said...

Something else is to guarantee your co-payer has the budgetary capacities. They ought to in like manner be adequately tried and true run with you in the midst of cruel times, and be thoughtful with your repayment issue. payday loans spring-valley

Alice Denny said...

The blog or and best that is extremely useful to keep I can share the ideas. Age Of War 2
Big Farm | Slitherio | Tank Trouble
Of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
Happy Wheels | Goodgeme Empire | Slither.io

94 hằng said...

Mostly people have all the same things when they are writing academic task or any other writing, especially light music most people like during the writing.

subway surf , baixar subway surf, subway surf download , download subway surf

94 hằng said...

Mostly people have all the same things when they are writing academic task or any other writing, especially light music most people like during the writing.
dream league soccer download , dream league soccer apk , download dream league soccer , dream league soccer

94 hằng said...

Thanks I have read your article, it is very interesting and exciting
download go launcher, go launcher apk, go launcher , go launcher androi,

94 hằng said...

You need to have time to take care of the active. It in fact was a amusement account it. Look advanced to far added agreeable from you.

banana kong download , banana kong , baixar banana kong , download banana kong , banana kong baixar

94 hằng said...

Life becomes more interesting and wonderful when you share your memorable moments with friends and family through unique photographs. You can create your own unique style impressed with image editing software. And after hours of work stress you can also
dr driving, dr driving baixar ,download dr driving, dr driving

94 hằng said...

Life becomes more interesting and wonderful when you share your memorable moments with friends and family through unique photographs. You can create your own unique style impressed with image editing software. And after hours of work stress you can also

tank trouble, tank trouble 2, tank trouble games, tank trouble

huong duong said...

Life has given us a precious gift, that is youth. A youth full of energy, expectation, desire, curiosity, struggle, hope and trust
b612 , play run 2 , geometry dash 2.0 , baixar snapchat , baixar musicas gratis

vishal bhagat said...

Buying LinkedIn Connections, Followers and Endorsements, is the most popular option for strengthening your professional identity. To find out a few guidelines regarding this, stay going through this web site. buylinkedin

manoj kumar said...

To find a greater publicity for your facebook account, People expend money to Buy Facebook Followers to conveniently obtain exposure on internet. buy followers on facebook

Jessica Jeon said...

To have a greater exposure to your facebook account, People expend money to Buy Facebook Followers to conveniently find hype online. order facebook followers