MongoDB Overview
- Document DB
- supports ACID
- uses JSON/BSON
- districuted scalability (sharding)
- high availability (replica set)
- free open source Community Edition
- pluggable storage engine support
- queries use MQL (MongoDB Query Language)
- has free text search capabilities
Terminology
Compared with Relational databases, MongoDB has the following terms:
SQL | MongoDB |
---|---|
Database | Database |
Table | Collection |
Row | Document |
Column | Field |
Index | Index |
BSON
BSON stands for “Binary JSON”, it’s binary-encoded. It sacrifies human-readability for performance. BSON supports more data types than traditional JSON (different numeric types, raw binary, dates, ObjectId, etc.).
Example:
# JSON{"hello": "world"}
# BSON\x16\x00\x00\x00 // total document size\x02 // 0x02 = type Stringhello\x00 // field name\x06\x00\x00\x00world\x00 // field value\x00 // 0x00 = type EOO ('end of object')
On the “frontend”, we talk with MongoDB in JSON. In the backend, MongoDB stores the documents as BSONs.
All the BSON types can be found in the MongoDB Docs.
Dates
A date can be represented in MongoDB with ISODate
.
{ "departureTime": ISODate("2019-05-07T09:13:00Z") "arrivalDate": ISODate("2019-05-08")}
We can use filtering based on date, including comparison operators such as
$gt
and $lt
.
Index
To create an index:
db.{collection}.createIndex( { name: 1 })
The index will be created on the name
field in ascending order.
We can get all indexes on a collection with:
db.{collection}.getIndexes()
Tools
Shell
Mongo Shell (mongosh) is a CLI interface for accessing MongoDB. It uses JS-like syntax.
mongosh "mongodb+srv://localhost/MyDatabase" --apiVersion 1 --username "myuser" --password "mypass"
Commands
db // Shows current DBshow dbs // Shows all DBs with storage sizeuse somedb // Switches context to some DB
show collections // Shows all collections in the current DBdb.createCollection("newcollection") // Creates a new collectiondb.{collection}.drop() // Removes a collection
db.{collection}.insertOne({ "name": "Marcin" }) // Creates a documentdb.{collection}.insertOne([{ "name": "Marcin" }, { "name": "Tom" }]) // Creates documents
db.{collection}.find() // Gets all documents in a collection
GUI
MongoDB Compass is the official GUI for exploring MongoDB databases. It’s available for Linux, macOS, Windows.
mongoimport
A tool that is added to MongoDB installations that allows for bulk imports of data.
Testing
MongoDB has MongoDB Atlas offering, which is a cloud deploymen of MongoDB. There’s a free tier that is shared, but great for testing. It can be deployed to Azure/GCP/AWS. For testing, we can also load a Sample Dataset.