Most of my database querying experience has either been with SQL Server or MySQL. But for a recent project, I ended up working with a mobile app that used a database stack, which included MongoDB and Elastic Search.

Like all good lessons, it all started with a mishap. I kept a reference document that contained syntax to query MongoDB on my computer. Rather than memorizing or attempting to understand the query syntax structure, I saved it in a document to copy and paste when I needed to run a query (I know, I know). And unfortunately, I didn’t keep a backup of the file, and of course, that’s when I lost it. So I bit the bullet and decided to teach myself MongoDB search syntax properly.


Here’s a few MongoDB query pointers that I learned along the way:

Tip 1: If you’re used to SQL, you’re familiar with “tables,” right? In MongoDB, these are called “collections.”

If you don’t know what MongoDB collection you need to query, then you can use:

show collections

This will give you a complete list of all the collections.

Tip 2: To increase the number of results that you get back from the query (the default is 20), use this syntax before you run the query again.

DBQuery.shellBatchSize = 100; (for 100 results, etc)

Tip 3: To make the results readable, append “.pretty()”.

For example:

db..find ( { : } ).pretty()

Tip 4: To use “and” in your query to find results that have multiple fields present with the values you’re querying, simply separate the two with a comma.

db.mycollection.find ( { age: “22”, hair: “brown” } ).pretty()

This will find all the people in the database that are 22 years old with brown hair.

Tip 5: You can use $gt (“greater than”) to add more specifics to your MongoDB query.

Our records used a “createdAt” field, along with a Unix time stamp. Searching using ‘greater than’ ($gt) found the data I needed, past the date I specified. This is what the query would look like in MongoDB:

db.mycollection.find( { age: “22”, hair: “brown”, createdAt: { $gt: 1437325492000} } ).pretty()

The above query will find all the results who are 22 with brown hair that were added to the database after the date specified. I personally use Epoch Converter to calculate the Unix time stamp to use in the query – but you can use any Unix timestamp conversion tool you prefer, if you’re searching by date.

There’s so much help out there, but this info got me to where I needed to be. The truth is, there’s no easy way to learn new things sometimes. You learn by diving in.