jLinq in MongoDB (Oh snap!!)

Yeah, you read that right - jLinq in MongoDB!

Lately I've been working on a Mongo database driver and I got to thinking -- Since I can use Javascript with MongoDB then I wonder if I could use jLinq to write queries? As it turns out the answer is yes!

... and if you don't know what jLinq is... - jLinq is a Javascript query language, similar to the LINQ project created by Microsoft, for JSON data which was designed to run within web pages using Javascript

Getting Started

I'm not really sure how you can get a Javascript library to load directly into MongoDB but for now I was simply copying and pasting the existing jLinq packed library into the command line and allowing it to evaluate the script -- and that is it! You can use jLinq right away!

You should be aware though that you can't just evaluate results directly. You actually need to call the toArray() function on each of them to see the results. So for example, your query would look something like...

jLinq.from(db.users.find().toArray()).startsWith("name", "h").select();

You don't need to actually do anything with the results since they are automatically displayed on the screen for you.

So far everything works. I could do standard queries, use the OR operator, reorder records, join different databases, perform comparisons against sub-properties -- really everything I've tried has worked just the way I'd expect it to!

Granted, database and collection names are going to be different, here are some interesting queries you can try with your database.

//Selects records where the name starts with a, b or c (case-insensitive)
jLinq.from(db.users.find().toArray())
    .startsWith("name", "a")
    .or("b")
    .or("c")
    .select();

//selects users older than 50 and are administrators then orders them by their names
jLinq.from(db.users.find().toArray())
    .greater("age", 50)
    .is("admin")
    .orderBy("name")
    .select();

//performs a join against another database to get locations
//and then queries the location to find users that live in 'texas'
//and then selects only the name of the person and location
jLinq.from(db.users.find().toArray())
    .join(db.locations.find().toArray(), "location", "locationId", "id")
    .equals("location.name", "texas")
    .select(function(rec) {
        return {
            person: rec.name,
            location: rec.location.name
        };
    });

Anyways, for now I'm not sure how to integrate jLinq into Mongo queries but keep an eye for future blog posts as I find out more.

February 14, 2010

jLinq in MongoDB (Oh snap!!)

Post titled "jLinq in MongoDB (Oh snap!!)"