Introduction
Welcome to Day 2 of 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 anyone 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.
You can read my previous article here.
Background
We covered the below topics of MongoDB in the first part of this article:
- Introduction of No-Sql (Different types of database comes under No-SQL)
- How to install and setup MongoDB on your machine.
- Introduction of Robomongo (MongoDB open source management tool)
- MongoDb Terminology
- How to insert a document in MongoDB
- How to select a document in MongoDB
Where
clause, Greater than and less than Like
, logical AND
and logical OR
in
operator in MongoDb, Count
and Sort
records in MongoDB Update
, Delete
, Remove
and Drop
in MongoDB Top
, Distinct
and Backup
in MongoDB
Some key points of MongoDB from my previous article:
- MongoDb is a Document Store database.
- MongoDB is Schema less.
- MongoDB Stores Data in JSON format (we call it BSON(Binary JSON)).
- JSON documents store data in Key Value Pair like
{“X”:1,”Y”:2,”Z”:3}
.
So it's time to cover some more mongodb concepts starting with the data types which we can use in MongoDB.
Takeaways of this Article
- Schema less behavior of MongoDB
$exists
$type
- Different Data Types of MongoDB
$in
, $all
and $nin
- Embedded documents and Query on Embedded documents
MongoDB is Schema Less
We always talk about that MongoDB Schema Less behavior and this is the key behavior for which MongoDB is so popular now a days. So let's understand the meaning of Schema less.
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 MongoDBDatabase
as below):
Insert a document in Employee
Collection:
db.Employee.insert({Name:"Vijay",Age:30,Email:"VijayRana1091@gmail.com"})
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
.
db.Employee.insert({Name:"Vijay",Age:30,Email:"VijayRana1091@gmail.com",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.
db.Employee.insert
({
Name:"Vijay",Age:30,Email:"VijayRana1091@gmail.com",
Address:"Delhi",Interest:["Cricket","Music"]
})
Wow, we can insert Array
as well in a document in MongoDB. Actually, there are two basic structures inside JSON:
Array
: List of things are represented in List of Items [……..] Dictionaries
: Associate Maps {key:Value}
So now, we are good with the concept of Schema less to go ahead.
As in the above example in some document, we can have Address
column and in another document in same collection, it's not necessary to have the same column. In short, in a Collection, different documents can have different columns/Schema. But 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 below:
In the above collection as 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 suppose I want to retrieve all the records where Address
exists.
Let me insert one more document in Employee
Collection as below:
db.Employee.insert
({
Name:111,Age:30,Email:"VijayRana1091@gmail.com",Address:"Delhi"
})
This time, I inserted an integer value in Name
column. Yes, we can do this as well. This is magic of Schema less nature. I can insert value of any type in any column.
But suppose I want to find out all the documents where name is in string
, how we will find out?
We have $type
for this.
$type
So far, we have the below records in my employee
collection. I have three documents where I have name
as a string
and one document where name
is in number.
Now, I want to find out all the documents where name
is in string
:
In mongodb, we use 2
for string
, 1
for number
. The 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 Type | Number | Meaning |
Double | 1 | For float values |
String | 2 | String is most commonly used DataType . In mongodb, string must be UTF-8 valid. |
Object | 3 | For embedded documents |
Array | 4 | For list or multiple values into one key |
Binary Data | 5 | To store binary data |
Undefined | 6 | |
Object Id | 7 | To store the document’s ID |
Boolean | 8 | To store a boolean (true /false ) value |
Date | 9 | To store date and Time |
Null | 10 | To store a Null value |
Regular Expression | 11 | To store regular expression |
32-bit integer | 16 | To store 32 bit Integer |
Timestamp | 17 | To store date and Time |
64-bit integer | 18 | To store 64 bit Integer |
Now what's next? Let me insert some more records
db.Employee.insert
({
Name:"Preeti",Age:26,Email:"Preeti@gmail.com",Address:"Delhi",
Interest:["cooking","Music"]
})
db.Employee.insert
({
Name:"Ajay",Age:26,Email:"Preeti@gmail.com",Address:"Delhi",
Interest:["Driving","Music"]
})
Now suppose we want to find out all the documents where interest is Music
, i.e., this time, we want to search inside an array.
We can search inside the array as well as below:
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
:
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 $in
operator:
db.Employee.find({Interest : {$in:["Driving","Music"]}})
If we want to find out all the records where interest is not cooking, then we will use $nin
as below:
db.Employee.find({Interest : {$nin:["cooking"]}})
The above query will return all the documents where Interest
is not cooking.
Embedded Document and Dot Notation
We can have embedded documents as well in MongoDB as below:
db.Employee.insert
({
Name:{firstName:"Preeti",LastName:"Rana"},Age:26,Email:"Preeti@gmail.com",
Address:"Delhi",Interest:["cooking","Music"]
})
db.Employee.insert
({
Name:{firstName:"Vijay",LastName:"Rana"},Age:30,Email:"Vijay@gmail.com",
Address:"Delhi",Interest:["cooking","Music"]
})
To specify a condition inside Embedded document, we can use dot notation as below:
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.
History
- 10th April, 2016: Initial version