MongoDB CRUD Operations
The basic methods of interacting with a MongoDB server are called CRUD operations. CRUD stands for Create, Read, Update, and Delete. These CRUD methods are the primary ways you will manage the data in your databases.
CRUD operations describe the conventions of a user interface that let users view, search, and modify parts of the database.
For those familiar with relational databases CRUD operations can be performed at the table, record, or column level. MongoDB is a NoSQL system; instead of tables it has a notion of collections, instead of records or rows in a table there are documents, and instead of columns documents have fields. So for MongoDB CRUD operations can be performed at the collection, document, or field level.
MongoDB documents are modified by connecting to a server, querying the proper documents, and then changing the setting properties before sending the data back to the database to be updated. CRUD is data-oriented, and it is standardized according to HTTP action verbs.
When it comes to individual CRUD operations:
- The Create operation is used to insert new documents in the MongoDB database.
- The Read operation is used to query a document in the database.
- The Update operation is used to modify existing documents in the database.
- The Delete operation is used to remove documents in the database.
How to Perform CRUD Operations with MongoDB?
Now that you have connected to your MongoDB database, and you know how MongoDB works, as well as what CRUD operations with MongoDB are, it’s time to take a look at how to manipulate documents in a MongoDB database using CRUD methods.
Let’s dive into the processes of creating, reading, updating, and deleting documents in a MongoDB server.
To follow along, you will need the following:
- MongoDB is installed on your server.
- Basic familiarity with the MongoDB shell will be used throughout this guide.
Before you begin:
- Connect to your MongoDB server using the MongoDB shell.
- Create a new MongoDB database using the use<database_name> command, or use an existing database.
For MongoDB CRUD, if the specified collection doesn’t exist, the create operation will create the collection when it’s executed. Create operations in MongoDB target a single collection, not multiple collections. Insert operations in MongoDB are atomic on a single document level.
MongoDB provides two different create operations that you can use to insert documents into a collection:
Creating a collection using create Collection
As the namesake, insertOne() allows you to insert one document into the collection. For this example, we’re going to work with a collection called RecordsDB. We can insert a single entry into our collection by calling the insertOne() method on RecordsDB. We then provide the information we want to insert in the form of key-value pairs, establishing the schema.
If the create operation is successful, a new document is created. The function will return an object where “acknowledged” is “true” and “insertID” is the newly created “ObjectId.”
It’s possible to insert multiple items at one time by calling the insertMany() method on the desired collection. In this case, we pass multiple items into our chosen collection (RecordsDB) and separate them by commas. Within the parentheses, we use brackets to indicate that we are passing in a list of multiple entries. This is commonly referred to as a nested method.
The read operations allow you to supply special query filters and criteria that let you specify which documents you want. The MongoDB documentation contains more information on the available query filters. Query modifiers may also be used to change how many results are returned.
MongoDB has two methods of reading documents from a collection:
In order to get all the documents from a collection, we can simply use the find() method on our chosen collection. Executing just the find() method with no arguments will return all records currently in the collection.
Here we can see that every record has an assigned “ObjectId” mapped to the “_id” key.If you want to get more specific with a read operation and find a desired subsection of the records, you can use the previously mentioned filtering criteria to choose what results should be returned. One of the most common ways of filtering the results is to search by value.
In order to get one document that satisfies the search criteria, we can simply use the findOne() method on our chosen collection. If multiple documents satisfy the query, this method returns the first document according to the natural order, which reflects the order of documents on the disk. If no documents satisfy the search criteria, the function returns null. The function takes the following form of syntax.
And, we run the following line of code:
We would get the following result:
Like create operations, update operations operate on a single collection, and they are atomic at a single document level. An update operation takes filters and criteria to select the documents you want to update.
You should be careful when updating documents, as updates are permanent and can’t be rolled back. This applies to delete operations as well.
For MongoDB CRUD, there are three different methods of updating documents:
We can update a currently existing record and change a single document with an update operation. To do this, we use the updateOne() method on a chosen collection, which here is “RecordsDB.” To update a document, we provide the method with two arguments: an update filter and an update action.
The update filter defines which items we want to update, and the update action defines how to update those items. We first pass in the update filter. Then, we use the “$set” key and provide the fields we want to update as a value. This method will update the first record that matches the provided filter.
updateMany() allows us to update multiple items by passing in a list of items, just as we did when inserting multiple items. This update operation uses the same syntax for updating a single document.
The replaceOne() method is used to replace a single document in the specified collection. replaceOne() replaces the entire document, meaning fields in the old document not contained in the new will be lost.
Delete operations operate on a single collection, like update and create operations. Delete operations are also atomic for a single document. You can provide delete operations with filters and criteria in order to specify which documents you would like to delete from a collection. The filter options rely on the same syntax that read operations utilize.
MongoDB has two different methods of deleting records from a collection:
deleteOne() is used to remove a document from a specified collection on the MongoDB server. A filter criteria is used to specify the item to delete. It deletes the first record that matches the provided filter.
deleteMany() is a method used to delete multiple documents from a desired collection with a single delete operation. A list is passed into the method and the individual items are defined with filter criteria as in deleteOne().