Query like A Pro — MongoDB Toolbox

shahar_avigezer

Shahar Avigezer

Posted on October 27, 2021

Query like A Pro — MongoDB Toolbox

Ever searched for a Mongo command and got a headache from all of those huge infinite tables? Here’s a simple guide with examples to get you talking to your Mongo shell smoothly

What is MongoDB?

MongoDB is a document database with the scalability and flexibility that you want along with the querying and indexing that you need.

Some MongoDB strengths you should know going in:

  • Stores data in flexible, JSON-like documents by a dynamic schema so the data structure can vary from from document to document in the same collection.

  • Holds a wide set of intuitive ad hoc queries helps to access and analyse the data easily and efficient indexing and real time aggregation.

  • Provides a document model that can be easily maps to objects in the application code.

Terminology

Database/dbs— A container that holds a group of collections. Notice that a single MongoDB server can have multiple databases for different purposes.

Collections — A group of documents which we later query. in SQL terms, the equivalent of a table.

Document/Object — A set of key-value pairs based in a dynamic schema which means that one document can have different set of key-value pairs than the other. in SQL terms, the equivalent of a single row in a table.

Get started

MongoDB Installation

You can install manually, I recommend to use Homebrew.

brew install mongodb
brew services start mongodb
Enter fullscreen mode Exit fullscreen mode

Mongo CLI Launch

The mongo shell is an interactive javascript shell so you need to have a basic knowledge in javascript to get started.

mongo
Enter fullscreen mode Exit fullscreen mode

We can use the default db or connect to our own new db

use mymongodb
Enter fullscreen mode Exit fullscreen mode

Operations & Queries

Language basics

A query will be structured by calling the db we are currently using, following up with the collection name, for example users and an operator like find() to read data from collection. Also, we can have functions to preform on our query result, for example count().

So, to retrieve the amount of objects in our users collection we can use:

db.users.find().count() 
Enter fullscreen mode Exit fullscreen mode

Add Data

As previously mentioned, what’s cool about Mongo is the dynamic style so if the collection does not exist, it will be created! Be careful by using the correct collection names to avoid duplicated.

To create a single objects in a collection we can use:

db.users.save({
"name" : "jenny",
"title" : "developer",
"company" : "google",
"age" : 24,
"address" : {
   "street" : "73 Pacific St.",
   "area" : "Forest Hills",
   "city" : "New York"
}
})
Enter fullscreen mode Exit fullscreen mode

Also, the operator insert can be useful here but I personally feel save is more useful since it can also preforms an update if there is a objects’ _id key that already exist in the collection. For inserting multiple objects, use insertMany([])by passing an array of objects.

Read Data

The better you know how to find, the less time you waste searching.

Let’s start easy, say we want to find our user “charlotte”:

db.users.find({ "name" : "charlotte" })
Enter fullscreen mode Exit fullscreen mode

Use And / Or by passing an array of expressions to match so we can find designers that are also named “dan”.

db.users.find({ $and: [
{ "name" : "dan" },
{ "title" : "designer" }
]})
Enter fullscreen mode Exit fullscreen mode

As we already established, we might have different set of key-value in our objects so let’s use exists to find only the users who have children:

db.users.find({ "children" : { $exists : true } })
Enter fullscreen mode Exit fullscreen mode

On certain values like numbers, we can use comparative operators such as grater than (gt) or less than (lt) ect. Let’s get all users who are exactly or above 18 years.

db.users.find({ "age" : { $gte : 18 } })
Enter fullscreen mode Exit fullscreen mode

Say we have a list of names of users we want to extract, you think we’re gonna find find find ?

Hell no! just use the super-powers of in operator:

var names = [ "michael", "jane", "abram", "justin", "diana" ]

db.users.find({ "name" : { $in : names } })
Enter fullscreen mode Exit fullscreen mode

Let’s find all users who have a more than one position in their title so we can use regex to track down the titles than contains “and”:

db.users.find({ "title" : /and/ })
Enter fullscreen mode Exit fullscreen mode

You’re not sure if it’s Capitalised? add /i to the end of the regex like so:

db.users.find({ "title" : /and/i })
Enter fullscreen mode Exit fullscreen mode

Modify Data

When we want to modify a property in an existing object, we pass the update() function 2 parameters: a key-value pair to match and a key-value pair to update.

Let’s make a user younger by changing his age:

db.users.update(
{ "name" : "erik" },
{ $set : { "age" : 24 }
})
Enter fullscreen mode Exit fullscreen mode

Must-know tip — Always use set otherwise you will change the whole object completely. Don’t fall for this one like I did!

We can also remove a property from an existing object by using unset, mind that the value is irrelevant since we’re removing the key-value altogether.

db.users.update(
{ "name" : "erik" },
{ $unset : {"age" : 0 }
})
Enter fullscreen mode Exit fullscreen mode

In case we want to change multiple objects, we will use multi as a third optional parameter to the function. Let’s transition all our developers to be dancers!

db.users.update(
{ "title" : "developer" },
{ $set : { "title" : "dancer" } },
{ multi : true }
)
Enter fullscreen mode Exit fullscreen mode

I heard Hawaii is great this time of year so let’s get all our analysts to relocate! When we want modify a nested object we can use . (dot annotation) like so:

db.users.update(
{ "title" : "analyst" },
{ $set : { "address.city" : "Hawaii" }
})
Enter fullscreen mode Exit fullscreen mode

Iterate Over Data

Most of the times we would want to go over big chunks of the data so what I found most effective is to convert our result to an iterable array:

var ctos = db.users.find({ "title" : "cto" }).toArray()
Enter fullscreen mode Exit fullscreen mode

And iterate with any of javascript for loops:

ctos.forEach(function(cto) {
  print(cto.name + " is a CTO at " + cto.company)
})
Enter fullscreen mode Exit fullscreen mode

Pro tips

By simply calling pretty() after your find() you can turn this view — >

db.users.find({ "name" : "jenny" })

{ "_id" : ObjectId("5ad34965b299eab765394481"), "name" : "jenny", "title" : "developer", "company" : "google", "age" : 24, "address" : { "street" : "73 Pacific St.", "area" : "Forest Hills", "city" : "New York" } }
Enter fullscreen mode Exit fullscreen mode

into the easy-on-the-eyes view:

db.users.find({ "name" : "jenny" }).pretty()

{
"_id" : ObjectId("5ad34965b299eab765394481"),
"name" : "jenny",
"title" : "developer",
"company" : "google",
"age" : 24,
"address" : {
"street" : "73 Pacific St.",
"area" : "Forest Hills",
"city" : "New York"
}
}

Enter fullscreen mode Exit fullscreen mode




Hope this guide was useful, feel free to share!

Follow me on Medium to learn how to improve your software development skills, or Connect with me on Linkedin and let me know if this guide helped you in any way, I’m always excited to hear your stories :)

Read more:

💖 💪 🙅 🚩
shahar_avigezer
Shahar Avigezer

Posted on October 27, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related