G-D00XZP85S3 How to Perform CRUD Operations in MongoDB - KangMus Official
Skip to content Skip to sidebar Skip to footer

How to Perform CRUD Operations in MongoDB

MongoDB provides its users with the ability to create modern databases that are easily accessed and manipulated.

MongoDB is a NoSQL open-source database that is available for use on all operating systems.

If you learned database design in school, chances are that you didn't learn how to use MongoDB or gain much experience with NoSQL databases. This comes as no surprise—up until 1998 many people hadn’t even heard about NoSQL, and it wasn't until 2009 that NoSQL databases started gaining traction.

What is NoSQL?

The acronym SQL stands for "structured query language." SQL is used to perform mathematical operations on data held in databases that are rigidly structured by rows and columns (tables).

The acronym NoSQL, depending on who you ask, stands for “not only SQL” or “non SQL.” However, the one fact that everyone can agree on is that NoSQL is used to perform operations on data that are held in databases not structured by rows and columns.

There are a few NoSQL databases in existence, but the name that stands above the rest is MongoDB. In fact, some people think that MongoDB is the only database of its kind.

What is MongoDB?

NoSQL supports four different types of databases: document, key-value stores, column-oriented, and graph. MongoDB is a document database because it stores data in a JSON-like document, and like all databases, it supports all the essential CRUD operations.

Related: How a MongoDB Database Can Better Organize Your Data

What are CRUD Operations?

The acronym CRUD stands for "create, read, update, and delete." CRUD represents the four basic functional requirements of all databases. If you’re using a database that doesn't allow you to create, read, update, or delete records, then it's not a database.

Download MongoDB

Before you can perform any CRUD operations in MongoDB, you'll need to download and install MongoDB on your device (or use an available cloud version), run the MongoDB server, connect to it, and finally create a new database.

The MongoDB server can be downloaded from the official MongoDB website.

Executing the MongoDB Server

Execute the MongoDB Server from the console of your IDE.


/Users/Administrator/mongodb/bin/mongod.exe --dbpath=/Users/Administrator/mongodb-data

The code above executes the MongoDB server. The first half provides the direct path to the MongoDB executable file (mongod.exe) that is stored on your device. The pathname on your device should be different, but the goal is to reach the mongod.exe file in the bin folder.

The second half of the code (which is separated by the space bar) is another pathname. This path leads to “mongodb-data”, which is a file that you'll need to create on your own. This file will contain all the data that is created in our database.

Our file is called “mongodb-data”, but the name can be whatever you think is suitable.

Executing the above code should produce several lines of code, but the two lines that you need to pay keen attention to can be seen below:


{"t":{"$date":"2021-04-14T18:10:11.779-05:00"},"s":"I", "c":"NETWORK", "id":23015, "ctx":"listener","msg":"Listening on","attr":{"address":"127.0.0.1"}}
{"t":{"$date":"2021-04-14T18:10:11.797-05:00"},"s":"I", "c":"NETWORK", "id":23016, "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}

These two lines contain the localhost and the default port of the MongoDB server, respectively. These two numbers are needed to later create a connection to the MongoDB server so we can perform our CRUD operations.

Performing CRUD Operations

Now that our MongoDB server is up and running, we can connect to it (using the appropriate driver) and start performing CRUD operations. For this article, we'll create a simple user database that will store the names and ages of our users.

Creating a User

There are two main ways to insert users into a MongoDB database. Both methods are fairly similar, but the method you should choose depends on the number of users you want to create in a specific instance. If your goal is to create one user, you should use the insertOne method.

However, if the goal is to create more than one user at a time, then the insertMany method is a better option.

MongoDB insertOne Method Example


// import mongodb and use destructuring to get the MongoClient function
const { MongoClient } = require("mongodb");
//the connection URL and the database that we intend to connect to
const connectionURL = 'mongodb://127.0.0.1:27017';
const databaseName = 'user-manager';
//using the connect function on the MongoClient to connect to the MongoDB server
MongoClient.connect(connectionURL, { useUnifiedTopology: true }, (error, client) =>{
//check if connection was established
if (error){
return console.log('Could not connect to database');
}
//access the user-manager database
const db = client.db(databaseName);
//insert one user into the database
db.collection('users').insertOne({
name: 'John Doe',
age: '28'
}, (error,result) =>{
if (error){
return console.log('Could not create user');
}
console.log(result.ops);
})
})

Before we can create any users, a connection has to be established with the MongoDB server using the MongoDB driver of the language you're using. The most popular driver, and the one that we're using in this tutorial, is the NodeJS driver.

With the first line of our code above, we're able to use the destructuring method to retrieve the MongoClient function from our server.

The MongoClient accepts three arguments:

  • A URL (used to connect to the MongoDB server)
  • Options/Settings (which in this case is setting the “useUnifiedTopology” variable to true, to facilitate the use of the new Server Discover and Monitoring engine)
  • A callback function that takes two arguments (error and client)

Within the callback function of the MongoClient method, we can finally insert a user into our database. But before we get to that point, we need to gain access to the user-manager database.

One of the beauties of using MongoDB is that there is no need to explicitly create a database. Once a reference to a particular database is generated using the “client” argument (as seen in the code above), you're free to start manipulating it.

The reference to the user-manager database that we generate is stored in the “db” variable, which we'll use to insert our first user into the database.

Using the “db” reference, we can create a new collection, which we assign the name "user".

The insertOne method takes two required arguments; the document (the user) and a callback function. With the insertOne method, we are able to insert a user by the name of Peter Davis with the age of 32, into our database.

The callback function takes two arguments (error and result). The result function contains an ops method which we use to see the user that we just created in our database. This produces the following output in the console, after the code above is executed:


[ { name: 'Peter Davis', age: '32', _id: 60772f869475e84740003c45 } ]

Though we only provided two fields when creating a user, you can see from the output above that a third field was generated. This is another cool thing about MongoDB; it automatically generates a unique id for every document that it creates.

Related: How Is Data Modeling Different In MongoDB?

Reading a User in MongoDB

The two main methods used to read documents from a MongoDB are: find and findOne. The find method is used to read multiple documents at a time and the findOne method is used to read a single document at a time.

MongoDB findOne Method Example


// import mongodb and use destructuring to get the MongoClient method
const { MongoClient } = require("mongodb");
//the connection URL and the database that we intend to connect to
const connectionURL = 'mongodb://127.0.0.1:27017';
const databaseName = 'user-manager';
//using the connect function on the MongoClient to connect to the MongoDB server
MongoClient.connect(connectionURL, { useUnifiedTopology: true }, (error, client) =>{
//check if connection was established
if (error){
return console.log('Could not connect to database') ;
}
//create the user-manager database
const db = client.db(databaseName);
//finding one user into the database
db.collection('users').findOne({name: 'Peter Davis'}, (error, user) => {
if (error){
return console.log('Could not find user');
}
console.log(user);
})
});

It's good to remember that you'll always need to connect to the MongoDB server and the appropriate database before you can perform any CRUD operations (as seen in our example above).

The findOne method takes two required arguments. The first argument contains the search criteria; you can search for a document using any variable name that is unique to it. In our example above we use the name “Peter Davis”.

The second argument of the findOne method is the callback function that takes two arguments; the first is an error if the document cannot be located, and the second one is the document (which we named "user").

Executing the code above will produce the following result in the console:


{ _id: 60772f869475e84740003c45, name: 'Peter Davis', age: '32' }

Updating a User in MongoDB

There are two available methods to update documents in MongoDB. Though the structure for both is very similar, updateOne is used to update one document at a time and updateMany is used to update many documents at a time.

MongoDB updateOne Method Example


//Update a user's age
db.collection('users').updateOne({ name: "Peter Davis"},
{
$set: {
age: '24'
}
})

With the code above we can update Peter Davis’ age to 24.

Deleting a User in MongoDB

There are two methods available for deleting a document from MongoDB. The deleteOne method is used to delete a single document, and the deleteMany method is used to delete multiple documents.

MongoDB deleteOne Method Example


//delete a document
db.collection('users').deleteOne({ name: 'Peter Davis'})

The delete operation is the simplest CRUD operation that can be performed in MongoDB. As you can see in the example above (not including the required connection code and callback function), it only takes one line of code.

You Can Now Perform CRUD Operations in MongoDB

Now you have basic knowledge of MongoDB, and you know what NoSQL means. You also know what the acronym CRUD stands for and why these operations are essential qualities of every database.

This article provides you with all the tools necessary to perform the four basic CRUD operations in MongoDB. Now that you're equipped with the CRUD operations know-how, you can begin learning how best to model your data using MongoDB.

Image Credit: Alexander Sosluev/WiKiMedia Commons



source https://www.makeuseof.com/crud-operations-mongodb/

Post a Comment for "How to Perform CRUD Operations in MongoDB"