Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / MongoDB

MongoDB Tutorial - Day 2

4.98/5 (29 votes)
11 Apr 2016CPOL5 min read 38.1K  
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 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:

  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.

Takeaways of this Article

  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:

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

C#
db.Employee.insert({Name:"Vijay",Age:30,Email:"VijayRana1091@gmail.com",Address:"Delhi"})

Here is the result:

Image 1

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.

C#
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:

Image 2

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.

Image 3

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

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

Image 4

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

Image 5

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

C#
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:

C#
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:

C#
db.Employee.find({Interest : {$all:["cooking","Music"]}})

Image 6

If we want to find out all the documents where Interest contains either music or driving, then we will use $in operator:

C#
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:

C#
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:

C#
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:

C#
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

License

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