MongoDB Basics

MongoDB Basics

MongoDB Introduction

MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas. MongoDB is developed by MongoDB Inc. and licensed under the Server Side Public License (SSPL).

Advantages of MongoDB

  • Flexible schema - you don’t need to declare a schema to use MongoDB. This is useful when it comes to storing unstructed data.
  • Scalability - MongoDB is a distributed database, so it can be horizontally scale with sharding.
  • Powerful querying and analytics - MongoDB allows users to easily query the database and rarely use joins and transactions.

When to avoid MongoDB

  • Multi Object Transaction - MongoDB only allows ACID transaction for a single document.
  • Relational data - If the dataset has many one-to-many or many-to-many relations and needs joins, you should use traditional SQL database instead.

Use cases

  • Personalization - track users search and activity to create personalized online experience.
  • Product Catelog, asset managements - we can store product or asset data and their metadata in MongoDB because of its flexible schema and powerful query capability.
  • IoT application - MongoDB is horizontally scalability makes it a better fit for data generated by IoT sensors. MongoDB also offers Time Series Collections for IoT applications.

Document and Collection

MongoDB is a document database so it stores records as Document. MongoDB stores documents as BSON. It is a JSON like document format.

Documents are organized as Collection. Collection is similar to Table in relational database.

Running MongoDB as Docker Container

Install using Docker

1
docker pull mongo

Running mongo container

1
docker run --name some-mongo -d -p 27017:27017 mongo

Running mongo container with username and password

1
2
3
4
5
docker run -d --name some-mongo \
-e MONGO_INITDB_ROOT_USERNAME=myusername\
-e MONGO_INITDB_ROOT_PASSWORD=mypassword\
-p 27017:27017 \
mongo

Use docker exec command to get shell access

1
docker exec -it [container-id] bash

You can now run mongodb command to start MongoDB Shell.

1
mongodb

To connect to MongoDB using username and password

1
mongodb -u myusername -p mypassword

The MongoDB Shell, mongosh, is a fully functional JavaScript and Node.js 16.x REPL environment for interacting with MongoDB deployments. You can use the MongoDB Shell to test queries and operations directly with your database.

MongoDB Compass is the GUI you can use to interact with MongoDB.

Database Commands

1
2
3
4
5
6
7
8
9
10
11
# show all databases in the server
show dbs

# show current database
db

# `use <db>` to switch databse
use test

# Removes the current database.
db.dropDatabase();

Collection Commands

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Show all collections
show collections

# create collection products
db.createCollection("products")

# show movie collection's stats
db.products.stats()

# drop products collection
db.products.drop()

# Count Documents in products Collection.
# query parameter is required for setting the criteria, pass {} to count all documenta
db.products.countDocuments({})

Document Commands

Insert

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# db.collection.insertOne() inserts a single document into a collection.
db.products.insertOne(
{
name: "Apple iPhone 13 Pro",
category: "Electronics",
price: 1000.00,
color: "Blue",
created: new Date()
}
)
# use db.collection.insertMany() method to insert multiple documents
db.products.insertMany([
{
name: "Samsung TV",
category: "Electronics",
price: 100.00,
created: new Date()
},
{
name: "Sleep Pillow",
category: "Home",
price: 100.00,
size: "King",
created: new Date()
}
])

Query

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# get all documents in a collection
db.products.find()

# find with query parameter: price is greater than 500
db.products.find({
price: {$gt: 50}
})

# find product that has category equals "Electornics" and price grreater than 50
db.products.find({
$and: [
{category: {$eq: "Electronics"}},
{price: {$gt: 50}}
]
})

# find using text search.
# Note that you need to create a text index before doing text search.
db.products.find( {$text: {$search: "iPhone"}})

$gt, $and, $text are all Query Selectors. specifically, $gt is comparison operator and $and is logical operator.

Update

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Modifies a single document in a collection.
db.products.updateOne(
{ "name" : "Sleep Pillow" },
{ $set: { "price" : 79.99 } }
)

db.products.updateMany(
{ "name" : "Sleep Pillow" },
{ $set: { "price" : 79.99 } }
)

# update by _id
db.products.updateOne(
{"_id" : ObjectId("629bb25a53cee9b4e83035a5")},
{$set: { "color": "green"}}
)

Delete

1
2
3
4
5
6
7
8
# delete a single document that match the condition that price is greater than
db.products.deleteOne({price: {$gt: 500}})

# delete by _id
db.products.deleteOne({"_id": ObjectId("629bb25b53cee9b4e83035a7")})

# delete all documents in products collection
db.products.deleteMany({price: {$gt: 500}})

Index Commands

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# create index with name price_idx
# specify index value 1 for ascending. -1 for decending
db.products.createIndex({price: 1}, {name: "price_idx"})

# create text index
db.products.createIndex({name: "text"}, {name: "name_idx"})

# get indexes
db.products.getIndexes()

# get index size
db.products.totalIndexSize()

# drop index
db.products.dropIndex("price_idx")

# drop indexes
db.products.dropIndexes()

createIndex can take a list of options. see Options for the complete list of options.

Reference