Simple Selections

MongDB queries look a bit different (okay a lot different) from its SQL counterpart. Where we once had standard SQL formats, datatypes, and ways of thinking, we now have a revolutionary way of doing things.

Firstly a database query is also a JSON string. This JSON string can be put into the find function of any collection:

db.SomeCollection.find()
// or 
db.SomeCollection.find({<some JSON query>})

The tricky part is finding out what goes inside the function. Let me explain with examples. Suppose we have the same two student objects in our SomeCollection collection:

    {
        student_number: 415324,
        name: "Susan",
        surname: "Strong",
        does_dancing: "yes",
        has_work_experience: "no"
    }

and

    {
        student_number: 9826421,
        name: "John",
        surname: "Smith",
        supervisor: "Prof Clev R. Guy",
        beers_per_day: 3
    }

If we wanted to do the equivalent of the old SQL:

SELECT * FROM SomeCollection;

Then the simple find would suffice:

db.SomeCollection.find()

This would return all the objects in the collection, which in our case is just the two students.

In order to find the student by name, which is done in SQL like this:

SELECT * FROM SomeCollection WHERE name = 'John';

We would use the JSON string together with the find() function in order to select only the second student:

db.SomeCollection.find({"name":"John"})

Leave a comment

Design a site like this with WordPress.com
Get started