Exploring MongoDB Query Language

Exploring MongoDB Query Language

MongoDB is a document-oriented NoSQL database program that allows you to store data in a Binary JSON format different from the Tabular format SQL databases are known for.

If you want to learn about SQL and NoSQL Database click this link.

MongoDB serves as a base that connects to an external application to query or collect the stored data. In the absence of an external application or framework like Express, MongoDB provides an internal Command Line Interface(CLI) called MongoDB shell that allows us to connect with the database to perform CRUD (Create, Read, Update and Delete) operations.

To get started with MongoDB, you have to first download MongoDB to your PC by visiting this link https://www.mongodb.com/try/download/community. After downloading, run the installation process which is quite intuitive.

After installation, if you visit your program files on your root directory, you find MongoDB with its packages, you can also verify your installation by going to your command prompt and running the prompt 'mongod –version'.

In your command prompt, run the command below, to initialize MongoDB Shell and gets it started.

mongo

Creating a database in MongoDB

There is no specific create database command in MongoDB, to make use of an existing database or automatically create one if none is available, you make use of the "use" keyword in MongoDB. For instance, if you want to connect to an already existing database called "School Database", you would just need to run the command "use School Database" in your MongoDB shell, if any of such databases doesn't exist, MongoDB will automatically create one and connect you to it. See the code below;

use schoolDatabase
//Expected output, switching to schoolDatabase
//I am using the Javascript CLI here, but, you would want to run this command in your MongoDB shell CLI.

To see your currently connected database, run the command;

show db
// Expected output is schoolDatabase

To see all the databases you have created including the three default "Local", "Admin" and "Config" databases, run the command below;

show dbs

You can also delete an entire base by running the command below;

db.dropDatabase():

Making use of Collections in MongoDB

MongoDB being a nonrelational database makes use of collections that comprise documents stored in JSON format. This unlike the structured approach of SQL which store data in rows and columns allows us to rather store a series of documents in what is called a collection.

The school database we created earlier can be seen as a collection, and we are next going to insert documents into it. See the command below;

db.schoolCollection.insertOne(
       {
              "schoolName" : "Kings College",
              "schoolLocation" : "Yaba"
       }
)
// If the insertion is successful it will return WriteResult({ “nInserted” : 1 }):

When successfully inserted, MongoDB will automatically generate a unique _id for each document, you don't need to manually create or attach an id.

Other methods of inserting a document in a collection are;

  • db.schoolCollection.insertOne

  • db.schoolCollection.insertMany

See the command for inserting many documents at once;

db.schoolCollection.insertMany([
       {
              "schoolName" : "Kings College",
              "schoolLocation" : "Yaba",
                "numberOfStudents": 54

       },
      {
              "schoolName" : "Methodist Girls College",
              "schoolLocation" : "Yaba",
               "numberOfStudents": 20
       },
   {
              "schoolName" : "Heritage College",
              "schoolLocation" : "Itam, Uyo",
               "numberOfStudents": 101
       }
])
// If the insertion is successful it will return WriteResult({ “nInserted” : 2 }):

HOW TO QUERY YOUR DATABASE IN MONGODB

From the above, we have created a database with a collection called 'school Collection', this collection currently has two documents that we inserted. Next, we want to look at how to query our collection to get documents;

We can find all the documents we created by running the command below;

db.schoolCollection.find()

The code above will give you a list of all the documents we created. But, we can as well filter our responses based on some query criteria.

Let's get back some documents base on the name. See the command below;

db.schoolCollection.find(
  {
    schoolName: "Kings College"
  }
)

This will give you the list of all documents that match the query parameter, which in our case is the school name, Kings College.

You can also query the collection to get results based on the number of students in each school. See the command below;

db.schoolCollection.find(
  {
    numberOfStudents: {$lt : 25}
  }
)
//Will give you a list of schools from the collection, where the numberOfStudents is less than 25

db.schoolCollection.find(
  {
    numberOfStudents: {$gt : 25}
  }
)
//Will give you a list of schools from the collection, where the numberOfStudents is greater than 25

db.schoolCollection.find(
  {
    numberOfStudents: {$lte : 25}
  }
)

//Will give you a list of schools from the collection, where the numberOfStudents is less than or eaqual to 25

To update the values of a single document, you can run the command below;

db.schoolCollection.updateOne({numberOfStudents: 20}, {$set: {numberOfStudents: 23}})

In the code above, will look for a document where the number of students is 20 and will update or set it to 23.

You can also remove a particular field from a document by first querying the collection for that particular document specifying then specifying the field you want to remove. See the command below;

db.schoolCollection.update({schoolName: "Kings College"}, {$unset: {numberOfStudents: ""}});

In the above, we are querying the collection based on the school name which is Kings Collection and also setting the number of students field to an empty field.

You can also remove a single document by specifying the criteria you want to identify the document with and even the whole documents in a collection by specifying an empty object, kindly see the code below;

db.schoolCollection.remove({schoolName: "Kings College"});
//This will remove a single document

db.schoolCollection.remove({});
// This remove a whole collection

Performing Logical Operations in MongoDB

Logical operations are operations that execute based on some given conditions. We have various logical symbols in MongoDB. They include;

NAME

DESCRIPTION

$and

Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.

$not

Inverts the effect of a query expression and returns documents that do not match the query expression.

$nor

Joins query clauses with a logical NOR returns all documents that fail to match both clauses.

$or

Joins query clauses with a logical OR returns all documents that match the conditions of either clause.

Now, let's use the $and to display schools whose location is at Yaba and their number of students is greater than 10. See the command below;

db.schoolCollection.find({$and:[{numberOfStudents : {$gt : 20}}, {schoolLocation: "Yaba"}]});

PERFORMING AGGREGATION IN MONGODB

Aggregation in MongoDB simply implies summarizing data based on various fields collected from various documents.

We could want to summarize the total number of schools from a particular location, this will need us to group all the documents inside our 'schoolCollection' collection based on a particular id which is the "schoolLoacation', then, sum it up.

See the code below;

db.schoolCollection.aggregate([
  {
    $group: {
      _id: "schoolLocation",
      result: { $sum: 1 }
    }
  }
]);

MongoDB Compass and ATLAS

MongoDB also provides a MongoDB compass you can use to keep track of your data offline on your desktop and a cloud-based database called ATLAS. You can download MongoDB Compass here and you can signup for Atlas here

In summary, MongoDB is a great NoSQL program for managing your database, and it provides a unique and dynamic approach for querying and updating your database. You can read more on MongoDB here,