Tutorials > First steps with MongoDB

First steps with MongoDB

Published on: 02 March 2021

Database Development

Introduction

In this guide, you will be presented with the main commands for managing a database built with MongoDB, intended for the management of high-performance applications and on the cloud.

MongoDB is a document-oriented NoSQL-type open source database, which differs from classic relational-type databases, such as its SQL alternative. MongoDB does not store data in tables with certain uniform fields, but allows you to save the records as a document where all the desired fields of any length can be added.

The tutorial will be based on the interaction with the database through the commands of the Mongo Shell but, if you are interested, other syntaxes are available according to the different editions.

Checking the database in use and changing it

In the shell, just type db to get the name of the database currently in use.

With the use command combined with the name of the database of your choice, the database in use will be changed.

Inserting, updating and deleting data in the Database

Inserting a document

The first step to record data is to insert a new document in your database.

For this purpose the following instruction can be used:

db.collection.insertOne()

Within the collection entry, specify the name of the collection (in case it does not exist, it will be created) where the new document will be inserted.

For example, imagine having a database that collects information about music and you want to add some music to one of the collections of favorite songs:

db.favorites.insertOne(
{ title: "Luna", artist: "Clementino", album: "Tarantelle", year: 2015, tags: ["rap","hiphop"] length: {m:3, s:25}})

The insertOne () entry returns a document with a new id field, automatically inserted by MongoDB.

Note: when specifying the values ​​of the fields, a square bracket has been opened in tags, and different values have been inserted. The syntax shown is for defining a field value with an array. This is the case of the genres with which the song is identified.

To retrieve the document, use the find command, as in the example:

db.favorites.find({title: "Luna"})

Using the words insert.Many multiple insertions can be performed with a single command :

db.favorites.insertOne(
{ title: "Luna", artist: "Clementino", album: "Tarantelle", year: 2015, tags: ["rap"] length: {m:3, s:25}}

{ title: "Breed", artist: "Nirvana", album: "Nevermind", year: 1991, tags: ["grunge"] length: {m:3, s:04}}

{ title: "The Boss", artist: "James Brown", album: "Black Caesar", year: 1973, tags: ["funk"] length: {m:3, s:15}}
)

To recall the documents just inserted, use an instruction similar to the first one, but without specifying the values ​​of the fields:

db.favorites.find({})

Updating document information

It may happen that an update or a replacement of some entity information registered in the database is needed. There are several methods to manipulate existing data and apply changes.

One of the most common methods is the use of the $ set operator, which allows you to change the value of a field. In addition, when that field does not exist in the document it creates a new one with the specified value. Let's look at a couple of operators in the example:

db.favorites.updateOne(
 { title: "The Boss" },
 {
 $set: { tags: ["boogie"]},
 $currentDate: { added: true }
 }
)

As shown, the first item that appears is updateOne, which updates the information of a single document. Following:

  • The {title: "The Boss"} line specifies which field and value to search for to select the document to edit
  • The $ set operator : specifies to change the value of the tags field with ["boogie"]
  • The $ currentDate operator will add the current date value to the added field and, if this field was not specified when creating the object, it will be created by the operator.

It is also possible to update multiple documents using the update.Many wording :

db.favorites.updateMany(
 { tags:["grunge"] },
 {
 $set: { tags:["rock"]},
 }
)

In the example, the command will update all the documents with tags equal to ["grunge"], inserting the new value ["rock"]

The last needed command is replace.One, which changes all the fields and values ​​in the document except its id.

The peculiarity of the command lies in avoiding the operator and simply having to enter the new fields and values. See the following example:

db.inventory.replaceOne(
{ title: "Luna"},
{ title: "Kalimba de Luna", artist: "Tony Esposito", album: "Kalimba de Luna", year: 1997, tags: ["pop"] length: {m:5, s:12}}

)

In the example, the replace instruction was performed by inserting the new values ​​into the already existing fields of the element with title Luna.

Deleting one or more documents

If necessary, MongoDB offers commands to delete one or more documents from the DB, also based on filter criteria.

The first command presented is:

db.favorites.deleteMany({})

If used without specification, the deleteMany command will delete all documents in the favorite collection.

The same instruction can be applied with a filter to the elements to be deleted.

db.favorites.deleteMany(
{ year: 2018 }
)
db.favorites.deleteMany(
{ "year": { $lt: 2018 } }
)

The above examples, respectively, perform:

  1. Erasing all songs of 2018
  2. Erasing all songs of years before 2018

The last variant is that of deleting a single element that corresponds to a filter applied to the fields.

db.favorites.deleteOne( 
 { artist: "Clementino" } 
 )

In this case, the first song by the artist Clementino from the collection has been canceled.

Extracting data from the database

Selecting all documents

To select all the documents, use an instruction that asks to extrapolate all the documents in a specific collection of a db:

db.favorites.find( {} )

In this case, all the data of the favorite collection are requested from the db.

Comparison of operators

Use operators to filter only the documents that have fields with a certain value.

To do so, reuse the find statement, specifying other conditions.

db.favorites.find( {tags: ["rap"]} )
db.favorites.find({title: "Luna"})

In the examples shown above, the commands serve respectively to:

  1. Recall all documents (your favorite songs) that have [rap] tags among them ;
  2. Call up the document titled Luna.

Query Operators

Within a filter, specify some query operators to specify other conditions in your search.

In case you want to compare the value of the same field with multiple values, the $ in operator can be used.

db.favorites.find({title: { $in: ["Luna","Kalimba"]}})

With this command, for example, the db will be requested to output the documents that have the word Luna or the word Kalimba in the title .

Linking multiple filters by AND

Logical operators can be used in MongoDB.

To use the AND operator, just use commas to separate the controls that have to be concatenated:

db.favorites.find( { artist: "Nirvana", year: { $lt: 1995 } } )

In the example above, the database is required to return favorite collection documents that have Nirvana as an artist and are from a year prior to 1995.

The syntax $ lt indicates the lower than operator, one of the comparison operators that can be used with MongoDB.

Filtering for different alternatives with the OR operator

The logical OR operator can also be used via the $ or command.

Going back to the command line from before:

db.favorites.find( { $or: [ { artist: "Nirvana"},{ year: { $lt: 1995 } } ] } )

The query extracts a document that has Nirvana as an artist or is a year prior to 1995.

Combining AND and OR

The example shows a command where ANDs and ORs are combined, to allow you to better understand a possible syntax for applying more complex filters.

db.favorites.find( { 
tags: ["rock"],	
$or: [ { artist: "Nirvana"},{ year: { $lt: 1995 } } ] } )

The query should select a rock song that is also from Nirvana or prior to 1995.

Aggregating the data

Data aggregation operations are based on the $ match and $ group operators, invoked by the aggregate command.

Basically, the $ match operator filters documents based on the required field value and outputs them in order.

The $ group operator, on the other hand, aggregates data based on the fields required in the syntax specification.

Below, an example to see how they work:

db.favorites.aggregate([
 { $match: { tags: ["rap"] } },
 { $group: { year: "$year", n_songs: { $sum: 1 } } }
])

In this code, the $ match operator filters and sorts all the songs that contain the rap voice in their tags. Subsequently, $ group groups all the songs of the same year and counts the number by adding, for each similar aggregate object, the value 1 to the n_songs field.

In natural language, the command asks you to group all the favorite rap categories by year of release and count the number of songs of that genre released in that year.

Conclusions

At the end of this guide, you should be able to use the most basic commands of the MongoDB shell and understand the different types of operations that can be performed to insert, manipulate or request data from the DB.

As the MongoDB database is constantly updated, it is suggested to explore the use of other operators and functions on the official MongoDB documentation.