MongoDB
What is MongoDB?
MongoDB is a document database. It stores data in a type of JSON format called BSON.
Example Document
{
title: "Post Title 1",
body: "Body of post.",
}
MongoDB is a document database and can be installed locally or hosted in the cloud.
MongoDB
MongoDB is a document database and can be installed locally or hosted in the cloud.
SQL vs Document Databases
SQL databases are considered relational databases. They store related data in separate tables. When data is needed, it is queried from multiple tables to join the data back together.
MongoDB is a document database which is often referred to as a non-relational database. This does not mean that relational data cannot be stored in document databases. It means that relational data is stored differently. A better way to refer to it is as a non-tabular database.
MongoDB stores data in flexible documents. Instead of having multiple tables you can simply keep all of your related data together. This makes reading your data very fast.
You can still have multiple groups of data too. In MongoDB, instead of tables these are called collections.
Local vs Cloud Database
MongoDB can be installed locally, which will allow you to host your own MongoDB server on your hardware. This requires you to manage your server, upgrades, and any other maintenance.
You can download and use the MongoDB open source Community Server on your hardware for free.
However, for this course we are going to use MongoDB Atlas, a cloud database platform. This is much easier than hosting your own local database.
To be able to experiment with the code examples, you will need access to a MongoDB database.
MongoDB Query API
The MongoDB Query API is the way you will interact with your data.
The MongoDB Query API can be used two ways:
CRUD Operations
Aggregation Pipelines
MongoDB Query API Uses
You can use the MongoDB Query API to perform:
Adhoc queries with
mongosh
, Compass, VS Code, or a MongoDB driver for the programming language you use.Data transformations using aggregation pipelines.
Document join support to combine data from different collections.
Graph and geospatial queries.
Full-text search.
Indexing to improve MongoDB query performance.
Time series analysis.
Create a new database called "blog":
use blog
You can create a collection using the
createCollection()
database method.Example
db.createCollection("posts")
Insert Documents
There are 2 methods to insert documents into a MongoDB database.
insertOne()
To insert a single document, use the
insertOne()
method.This method inserts a single object into the database.
insertMany()
To insert multiple documents at once, use the
insertMany()
method.This method inserts an array of objects into the database.
Find Data
There are 2 methods to find and select data from a MongoDB collection,
find()
andfindOne()
.find()
To select data from a collection in MongoDB, we can use the
find()
method.This method accepts a query object. If left empty, all documents will be returned.
findOne()
To select only one document, we can use the
findOne()
method.This method accepts a query object. If left empty, it will return the first document it finds.
Update Document
To update an existing document we can use the
updateOne()
orupdateMany()
methods.The first parameter is a query object to define which document or documents should be updated.
The second parameter is an object defining the updated data.
Delete Documents
We can delete documents by using the methods
deleteOne()
ordeleteMany()
.These methods accept a query object. The matching documents will be deleted.
MongoDB Query Operators
There are many query operators that can be used to compare and reference document fields.
Comparison
The following operators can be used in queries to compare values:
$eq
: Values are equal$ne
: Values are not equal$gt
: Value is greater than another value$gte
: Value is greater than or equal to another value$lt
: Value is less than another value$lte
: Value is less than or equal to another value$in
: Value is matched within an array
Logical
The following operators can logically compare multiple queries.
$and
: Returns documents where both queries match$or
: Returns documents where either query matches$nor
: Returns documents where both queries fail to match$not
: Returns documents where the query does not match
Evaluation
The following operators assist in evaluating documents.
$regex
: Allows the use of regular expressions when evaluating field values$text
: Performs a text search$where
: Uses a JavaScript expression to match documents
MongoDB Update Operators
There are many update operators that can be used during document updates.
Fields
The following operators can be used to update fields:
$currentDate
: Sets the field value to the current date$inc
: Increments the field value$rename
: Renames the field$set
: Sets the value of a field$unset
: Removes the field from the document
Array
The following operators assist with updating arrays.
$addToSet
: Adds distinct elements to an array$pop
: Removes the first or last element of an array$pull
: Removes all elements from an array that match the query$push
: Adds an element to an arrayAggregation Pipelines
Aggregation operations allow you to group, sort, perform calculations, analyze data, and much more.
Aggregation pipelines can have one or more "stages". The order of these stages are important. Each stage acts upon the results of the previous stage.
Example
db.posts.aggregate([ // Stage 1: Only find documents that have more than 1 like { $match: { likes: { $gt: 1 } } }, // Stage 2: Group documents by category and sum each categories likes { $group: { _id: "$category", totalLikes: { $sum: "$likes" } } } ])
Indexing & Search
MongoDB Atlas comes with a full-text search engine that can be used to search for documents in a collection.
Atlas Search is powered by Apache Lucene.
Creating an Index
We'll use the Atlas dashboard to create an index on the "sample_mflix" database from the sample data that we loaded in the Intro to Aggregations section.
From the Atlas dashboard, click on your Cluster name then the Search tab.
Click on the Create Search Index button.
Use the Visual Editor and click Next.
Name your index, choose the Database and Collection you want to index and click Next.
If you name your index "default" you will not have to specify the index name in the
$search
pipeline stage.Choose the
sample_mflix
database and themovies
collection.
Click Create Search Index and wait for the index to complete.
Running a Query
To use our search index, we will use the $search
operator in our aggregation pipeline.
Example
db.movies.aggregate([
{
$search: {
index: "default", // optional unless you named your index something other than "default"
text: {
query: "star wars",
path: "title"
},
},
},
{
$project: {
title: 1,
year: 1,
}
}
])