Big Data Series: Querying JSON with MongoDB

Let’s use the above example as our JSON script on which we’ll base our queries. Before we get started, let’s cover of the core components of a MongoDB query.

DB.COLLECTION.FIND(<QUERY FILTER>, <PROJECTION>). CURSOR MODIFIER

So, lets go through each component:

    • Collection is like the table name in a relational DB. In the above, our collection would be ‘Artists’.
    • Query Filter: is like the where clause in an SQL query. It’s the condition that you wish to apply. If there are no conditions, we can just leave this blank e.g. .find().
    • Projection: these are the variables to return just like in the select clause of an SQL query. SELECT Artist, Age….
    • Cursor Modifier: this limits the results you wish to return

Right, so let’s get into some examples to make this a bit clearer.

MongoDB Logical Operators:

SQL Like vs MongoDB Regex


We can go even further with this. We could say ‘show me all records that start with ‘Em’ and end in ‘em’.To do that, we would query:
Db.artists.find(Artist:{$regex:/^Emin.*em$/}); where the . denotes any character and * denotes that any character can happen any number of times.

We can also start querying arrays within the JSON:

We can now start adding lots of operators into our queries, like below:

Db.artists.find({

 

The above query says: return all records where the price is 10 or 11; the artist is Eminem or Kano and the format is not equal to MP3.

 

Kieran Keene

view all posts

Join me on this career development project as I set out to develop the skills required to progress up the technology career ladder! Check out http://netshock.co.uk/about/ to find out more.