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.

59 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

Unknown 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.

Unknown 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

Unknown 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

Unknown 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.

Anonymous 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.

Unknown 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

Unknown said...

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

Unknown 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

Unknown 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

Unknown 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

Unknown 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

Unknown 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

Unknown 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

Unknown 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

Unknown said...

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

Unknown said...

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

Unknown 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

Unknown 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

Unknown 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

Unknown 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

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

Unknown 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

Unknown 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

Unknown 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

Unknown said...

B erl face serum

Drag Racer V3 said...

Thank you very much. stick-rpg2.com

Potty Racers 2 said...

This makes it ideal for fast response and initial validation of form input. pianotiles2.com

Unknown said...

Tali Tambang Kapal Bekas

Unknown said...

jasa pengurusan SBU

Mas Aguz said...

Informasi yang sangat menarik Toko wallpaper Jakarta

alicetaylor123 said...

The blog or and best that is extremely useful to keep I can share the ideas 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.

supersmashflash2s.com

Carruth Vallecillo said...

Moreover, most moneylenders will expect you to think of them a check for the measure of the advance in addition to charges, which they will hold until the point that your next payday at which time they will store the check and get their "pay back." usapaydayloanstore.com/chicago

Unknown said...

How would you settle if MongoDB Configuration document not working? Contact to MongoDB Technical Support

Well people, if your MongoDB arrangement record isn't working then the primary thing is to check Windows occasion watcher and see what's occurring there. In the event that as yet happening a similar issue at that point endeavor to contact MongoDB Online Support or MongoDB Customer Support USA. Here we give out-of-box support to our important clients where we proactively check your whole database and resolve a wide range of obstruction specialized issues. Our Support for MongoDB Database Software is exceptionally moderate, financially savvy and easy to understand. Rapidly contact to us by means of dialing our number and investigate the best help through our expert specialists.

#mongodbjsonsupport #MongoDBDatabaseSoftware #mongodbtechnicalsupport #SupportforMongoDB
#mongodbonlinesupport #mongodbcustomersupportusa #mongodbsupport #SupportforMongoDBDatabaseSoftware

For More Info: https://cognegicsystems.com/
Contact Number: 1-800-450-8670
Email Address- info@cognegicsystems.com
Company’s Address- 507 Copper Square Drive Bethel Connecticut (USA) 06801

D'Chuz said...

Good article. souvenir boneka

Unknown said...

facebook is most famous social applications it is give a good platform to make popular yourself if you want facebook followers you can easily purchase here purchase facebook followers

sagar90 said...

Lots of start-ups are working really tough to create a mark for themselves in the blockchain domain. ico white paper writer

Alwin Co Daan said...

Great Article
B.Tech Final Year Projects for CSE in JavaScript

FInal Year Project Centers in Chennai

JavaScript Training in Chennai
JavaScript Training in Chennai

Alodia said...

Kunjungi Situs Gaming Online dengan deposit termurah, proses tercepat dan penarikan tanpa batas maksimal, Daftar Sekarang disini:

Daftar SCR888
Download SCR888 Apk
Daftar 918Kiss
918Kiss

youtubecomactivate said...

Nice Post.
You can start the channel and get the channel activation code to enter on youtube.com/activate website. Once you accomplish this process, then you are ready to watch YouTube videos on your Device.

Gregory Carney said...

I really enjoyed reading your article. I feel like I have a problem doing it on the keyboard. However, many people should have come, so consider sharing this keyboard check profile checker with a keyboard tester.