MongoDB Tutorial - Queries: Part Two

Introduction

Welcome to Day Two of my MongoDB tutorial. This is the second part in the MongoDB tutorial series. In the first part of this article, we covered and learned some basic queries and operations of MongoDB . In the last article, we compared some SQL queries with MongoDB queries. If somebody is new to MongoDB, then it will be good to go through my previous articles before this. In this article, we will see some MongoDB specific queries.

Background

You can learn more about MongoDB.

We covered the below topics of MongoDB in the first part of this article,

  1. Introduction of No-Sql (Different types of database comes under No-SQL)
  2. How to install and setup MongoDB on your machine.
  3. Introduction of Robomongo (MongoDB open source management tool)
  4. MongoDB Terminology
  5. How to insert a document in MongoDB
  6. How to select a document in MongoDB
  7. Where clause, Greater than and less Than
  8. Like, logical AND and logical OR
  9. In operator in MongoDB , Count and Sort records in MongoDB
  10. Update, Delete, Remove and Drop in MongoDB
  11. Top, Distinct and Backup in MongoDB

Some key points of MongoDB from my previous article,

  1. MongoDB is a Document Store database.
  2. MongoDB is Schema less
  3. MongoDB Stores Data in Json Format (we call it BSON(Binary JSON))
  4. JSON documents store data in Key Value Pair like {“X”:1,”Y”:2,”Z”:3}

Hence, it's time to cover some more MongoDB concepts, starting with the data types, which we can use in MongoDB .
Takeaway of this article will be:

  1. Schema less behavior of MongoDB
  2. $exists
  3. $type
  4. Different Data Types of MongoDB
  5. $in, $all and $nin
  6. Embedded documents and query on embedded documents

MongoDB is schema less

We always talk about the MongoDB schemaless behavior and this is the key behavior for which MongoDB is so popular, nowadays. Let's understand the meaning of schemaless.

Suppose we have a collection named Employee in our test database (Please go through my previous article to know how to create database and collection in MongoDB Database, as shown below):

Insert a document in Employee Collection:

  1. db.Employee.insert({Name:"Vijay",Age:30,Email:"[email protected]"})  
In the above document, we have Name, Email as String and Age as number.

Now let me insert one more document and this time I will add one more column named address.
  1. db.Employee.insert({Name:"Vijay",Age:30,Email:"[email protected]",Address:"Delhi"})  
Here is the result:



Now just think about RDMS. In case of RDMS, we had to Alter the table first to add a new column but in case of MongoDB , we don't need to add a new column because all the documents can have different schema in MongoDB.

Let me insert one more document in Employee Collection.
  1. db.Employee.insert  
  2. ({  
  3.    Name:"Vijay",Age:30,Email:"[email protected]",Address:"Delhi",Interest:["Cricket","Music"]  
  4. })  
Wow, we can insert array as well in a document in MongoDB . Actually, there are two basic structures inside JSON:

 

  1. Array: List of things are represented in list of Items [……..]
  2. Dictionaries: Associate maps {key:Value}

Hence, we are good with the concept of schemaless, and good to go ahead.

As in the above example in some document, we can have Address column and in another document in the same collection, it's not necessary to have the same column. In short, in a collection, different documents can have different columns/schema. Suppose you want to find out all the documents in a collection where Address column exists. In MongoDB , we have $exist for such queries.

$exists

We have Employee collection, as shown below:



In the above collection, as shown below, suppose I have some documents, where we don't have Address and some documents where we have Address column along with other columns. Now, I want to retrieve all the records where Address exists.



Let me insert one more document in Employee Collection, as shown below:

  1. db.Employee.insert  
  2. ({  
  3.    Name:111,Age:30,Email:"[email protected]",Address:"Delhi"  
  4. })  
This time, I inserted an integer value in Name column. Yes, we can do this as well. This is the magic of schemaless nature. I can insert value of any type in any column.

Suppose, I want to find out all the documents where the name is in string, how we will find out?

We have $type for this.

$type

So far, we have the records, shown below, in my employee collection. I have three documents, where I have name as a string and 1 document, where name is in number.



Now, I want to find out all the documents, where the name is in string:



In MongoDB , we use 2 for string, 1 for number. Complete list of all the data types are shown in the below table.
We can use the below data types in $type.

Data Types in MongoDB

Some of the commonly used data types in MongoDB are as follows:
 
Data TypeNumber Meaning
Double 1For float values
String 2String is most commonly used DataType. In MongoDB , string must be UTF-8 valid.
Object 3For embedded documents
Array 4For list or multiple values into one key
Binary Data5To store binary data
Undefined 6 
Object Id 7To store the document’s ID
Boolean 8To store a boolean (true/false) value
Date 9To store date and Time
Null 10To store a Null value
Regular Expression 11To store regular expression
32-bit integer16To store 32 bit Integer
Timestamp 17To store date and Time
64-bit integer 18To store 64 bit Integer

Now, what's next? Let me insert some more records:

  1. db.Employee.insert  
  2. ({  
  3.    Name:"Preeti",Age:26,Email:"[email protected]",Address:"Delhi",Interest:["cooking","Music"]  
  4. })  
  5.   
  6. db.Employee.insert  
  7. ({  
  8.    Name:"Ajay",Age:26,Email:"[email protected]",Address:"Delhi",Interest:["Driving","Music"]  
  9. })  
Suppose, we want to find out all the documents; where the interest is music, i.e., this time we want to search inside an array.
We can search inside the array as well as shown below:
  1. db.Employee.find({Interest : "Music"})  
So, we can say our matching is Polymorphic in MongoDB.

$in, $all and $nin

If we want to find out all the documents where we have both cooking and music as an interest, then we can use$all:


  1. db.Employee.find({Interest : {$all:["cooking","Music"]}})  
If we want to find out all the documents where Interest contains either music or driving, then we will use $inoperator:
  1. db.Employee.find({Interest : {$in:["Driving","Music"]}})  
If we want to find out all the records wher e the interest is not cooking, then we will use $nin as below:
  1. db.Employee.find({Interest : {$nin:["cooking"]}})  
The above query will return all the documents, where the interest is not cooking.

Embedded Document and Dot Notation

We can have embedded documents as well in MongoDB, as shown below:
  1. db.Employee.insert  
  2. ({  
  3.    Name:{firstName:"Preeti",LastName:"Rana"},Age:26,Email:"[email protected]",  
  4.    Address:"Delhi",Interest:["cooking","Music"]  
  5. })  
  6.   
  7. db.Employee.insert  
  8. ({  
  9.    Name:{firstName:"Vijay",LastName:"Rana"},Age:30,Email:"[email protected]",  
  10.    Address:"Delhi",Interest:["cooking","Music"]  
  11. })  
To specify a condition inside embedded document, we can use dot notation, as shown below:
  1. db.Employee.find({"Name.firstName":"Vijay"})  
The above query will search all the documents where we have firstName as Vijay inside Name.

In the next article of this series, I will cover aggregation(groupBy), indexes, $Text and $lookup. So, stay tuned. 


Similar Articles