Click here to Skip to main content
14,217,648 members

MongoDB Tutorial - Day 2

Rate this:
4.98 (29 votes)
Please Sign up or sign in to vote.
4.98 (29 votes)
11 Apr 2016CPOL
MongoDB Tutorial - MongoDB specific queries

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 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.

You can read my previous article here.

Background

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}

So 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 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:

  1. Array: List of things are represented in List of Items [……..]
  2. 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 3 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 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 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

VijayRana
Technical Lead
India India
Hi Myself Vijay having around 7 years of experience on Microsoft Technologies.

Comments and Discussions

 
GeneralMy vote of 5 Pin
AJSON12-Apr-16 9:55
mvaAJSON12-Apr-16 9:55 
GeneralGood One!!!! Pin
Rishi Jhunjhunwala11-Apr-16 2:30
memberRishi Jhunjhunwala11-Apr-16 2:30 
PraiseNice article Pin
Shraddha Shree10-Apr-16 7:27
memberShraddha Shree10-Apr-16 7:27 
PraiseGood work Pin
PreetiRana10-Apr-16 6:47
memberPreetiRana10-Apr-16 6:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 10 Apr 2016

Stats

25K views
26 bookmarked