MongoDB Commands

,

Mongo DB is a database of documents with the scalability and flexibility you want with the query and indexing you need. It is part of the NoSQL database systems.

In this artical, I would like to share some of the basic questions about MongoDB commands, such as queries, filtering, deleting, updating and so on.

To use MongoDB, it must be installed on your computer. To do this, check out this article I posted previously. https://wisecodes.venuthomas.in/2023/02/04/mongodb-server-and-compass-installation-guide-for-windows-11/

The Database

RDBMS (Relational Database Management Systems) provides databases, tables, rows and columns.

However, in NoSQL databases, like MongoDB, data is stored in BSON format (a binary version of JSON). They are stored in structures called “collections”.

In SQL databases, these would look like tables.

SQL vs MongoDB

Basic MongoDB Commands

Let’s start by talking about some basic MongoDB commands. To start the mongo service

mongod

NOTE: Open another terminal and let them perform the MongoDB service.

After you have initialized the Mongo service, type the terminal: Mongo, with this command you will launch the Mongo shell, leaving the terminal available to execute the commands.

mongosh

List all databases

show databases

This command shows us all the databases which have been created in our cluster.

List all collections

show collections

This command shows us the collections available in the database, remember to first select the database with the use command.

Create a database or use an existing one

use <dabase name>

It should be clarified that MongoDB does not create empty databases, if you want the database to materialize, you must create a document.

CRUD Operations in MongoDB

CRUD is an acronym for Create, Read, Update and Delete.

You will see that these CRUD commands in MongoDB will be the same as those we will use to control CRUD operations for our NodeJS applications.

In these operations, we will obviously use JSON. Underneath, MongoDB uses BSON to store and transfer.

Create

We can insert data in a new collection or in an already created collection.

How to store data in a JSON: key-value pairs, string arrays, objects, and object arrays.

There are three ways in which data can be inserted.

  1. insertOne(): is used for single document insertion.
  2. insertMany(): is used for inserting multiple documents.
  3. insert(): allows you to insert as many documents as you like.

Some examples are as follows:

  • insertOne()
  • insertMany()
  • insert()

The insert() method is similar to the insertMany() method.

The syntax of the command is:

db.<collection name>.insert( <document in JSON format>);

If there weren’t any collections, MongoDB would create it.

The Insert() function accepts a JSON object as a parameter, so it’s possible to do something like this:

If all of our records have been inserted correctly without a rollback occurring, MongoDB can expect an array of objects to confirm that they have been created correctly by sending back the _id of each object in response.

Read

Here’s how you can query all the data in a collection.

There are two ways to search for documents, we can make it through filters or directly by the _id

  1. find(): It return one or more documents that comply with certain conditions that we indicate. If no search conditions are specified, all records in the collection will be returned to us.
  2. findOne(): A single document that meets certain conditions will be returned. If no search conditions are specified. It will return the last document in the collection.

Some examples are as follows:

  • find()
  • findOne()

The syntax of the command is:

db.<collection name>.find();
db.<collection name>.find(<filter>);

In addition to filtering by the fields of the collection itself, Mongo offers several operators that allow you to refine searches. For example, If you want to display only people whose age is less than 15. You can use $lt to filter that way. $lt operator represents “less than” and $gt represents “greater than”.

There are several operators that allow different filtering, all of which are explained here Query and Projection Operators.

Finally, to count the results (the equivalent of the SQL COUNT) there is the count() function.

Update

To modify existing documents, we can use 3 methods:

  1. update()
  2. updateOne()
  3. updateMany()

Some examples are as follows:

  • update()

The syntax of the command is:

 db.<collection name>.update(<filter>, <update>)

The <filter> argument should contain the condition for deciding which documents to update. for example a valid filter could be the _id or another could be all documents with less than 40 parts.

It is always better to use something like the _id field to update a single line. This is so because different fields can have the same values for name and age. Likewise, if you update a single line, it will affect all the lines that have the same name and the same identity.

In the <update> argument, the fields we want to update can be one of several fields that we can update. Those fields have to follow the operator. $set.

For example, If you want to update a employee’s age

One of the more interesting options in this update is upsert. If we activate this parameter, the update can behave like an insertion if the filter is not filled.

Let’s imagine that we make an update by _id in our collection, but it turns out that the id does not exist. If we do not activate the upsert option, the values we pass to update will have no effect on the database. However, if upsert is activated, Mongo will create a new document from these data.

A field that is no longer needed can be deleted by executing the update() function with the $unset operator and specifying the fields to be deleted.

updateOne() and updateMany() methods that similarly work similarly to findOne() and find().

Delete

Finally, the last of the CRUD operations, the elimination. There are three ways to delete documents

  1. remove()
  2. deleteOne()
  3. deleteMany()

Some examples are as follows:

  • remove()

The syntax of the command is:

db.<collection name>.remove(<filter>)

As I mentioned before, when you want to update or delete a document, just specify the _id, not just name or age.

Calling remove() with the search filter {} will delete all the documents from the collection.

Like insert and update, it has methods to delete one element and multiple: deleteOne() and deleteMany(). And both methods only receive one parameter: the filter to select the documents to be deleted.

There are more commands and queries that we can do in MongoDB but to begin with this would be the essential thing.

If you would like to ask me questions, please feel free! I’ll always have my mailbox open. Whether you have a question or would like to simply say hello. I will do my utmost to respond!

Please follow and like us:
1

Leave a Reply

Your email address will not be published. Required fields are marked *