Working with any database always requires some CRUD. Learn how to connect to a MongoDB database and perform basic data transactions.
Database technology is a subject that can quickly become complicated, but here, we’re going to stick to the basics. For example, on a very high level, you’ll usually want to do the same few things repeatedly, that is: connect to a database, insert or update one or more records, or delete one or more records. This is otherwise known as “CRUD” (“create read update delete”). Now even though the exact syntax for these actions will differ from one database technology to the next, the good news is that the general concepts are the same.
In this article, I’ll demonstrate very basic MongoDB CRUD operations using the MongoDB Node.JS Driver. Let me just begin, however, by mentioning the part that I’ll be leaving out: the “U” (“update”) step of our CRUD operations. This is a practical move on my part, because I’m guessing that you no doubt found this article through a web search, and you’re perhaps just getting started with MongoDB. If this is the case, then I think the “create,” “read,” and “delete” steps in this article are the best ones to begin with, and I will follow up with an article dedicated specifically to the more challenging “update” operations in MongoDB. That said, let’s just dive right into some MongoDB CRUD (minus the “U” : – )
Connect to the Database – Example # 1
In Example # 1 we connect to the madMen database. There are just a few steps needed to set up the connection. On line #s 2, 3 and 4 we have the URL of the database server, the name of the database we want to connect to, as well as the name of the collection with which we want to work. On line # 7 we use the mongoDbClient object that was created on line # 1 and we call its connect() method, passing it the database url. The second argument that we pass to mongoDbClient.connect is a callback which will allow us to act upon a successful connection. Now our reason for needing the callback function is that the mongoDbClient.connect method is asynchronous. So inside of the callback function, we execute a console.log() statement just to let ourselves know that were able to establish the connection. Now there’s not too much going on here; I just wanted to point out the basics of how to connect to the database. Once again, just keep in mind that connecting to the MongoDB database is an asynchronous operation.
Insert a New Document – Example # 2
Example # 2 takes us to our next logical step in our CRUD operations by having us insert a new document into the database. The required steps for connecting to the database are exactly the same as those for Example # 1, so let’s save some time, skip over that, and talk about what’s new in Example # 2. Here, we’re using the database variable, which is the second argument passed to the mongoDbClient.connect callback function. Now, in using that database variable, we get ahold of the madMen database, and also set a reference to the names collection. So, using that variable, we call the collection.insert method, passing it the new document that we want to insert, as well as a callback function. Now the hope is that by now, you’ve noticed a pattern, which is that we need to provide a callback function because the collection.insert method is asynchronous. In the callback that we pass to the collection.insert method, we use console.log() to indicate that the document that was inserted was successful. This, of course, is just for demonstration purposes. We then call the database.close() method, to close the database connection.
Insert Multiple Documents – Example # 3
There is only a small difference between Example #s 2 and 3, and that is in Example # 3 we use the collection.insertMany method instead of collection.insert. And instead of passing one document, we pass an array of documents. Everything else is virtually the same; i.e., we execute a log message for demonstration purposes and then close the database connection.
View All Documents – Example # 4
So, now that we have created a few documents, it’s time to view them. Let’s take a look at Example # 4, and drill down to the collection object. By getting ahold of the collection, we can use its find() method. And by passing no arguments to the find() method, we get all of the documents in the collection. We iterate that list of documents, and output each one in the console. Then, when we have gotten to the end of the list, we close the database connection.
Delete One Document – Example # 5
So here we are at CRUD’s letter “D”, which is what we take care of in Example # 5. The main difference between this one and Example # 4 is that once we drill down to the collection object, we use the deleteOne() method, passing it an object that represents the document that we want to delete. Now, I say “…object that represents” because we do not pass it the exact document that we want to delete; what we actually pass it is an object that contains the ID that matches the document we want to delete. Note here that in this document the value of the _id property is an instance of ObjectID, which we initialized on line # 2. ObjectID is a special object that we need in order to pass around mongoDB document IDs. Now it’s important to point out that while it may be tempting to simply pass the ID of the document that we want to delete, unfortunately, MongoDB does not work like that. You need to actually provide an instance of ObjectID. It’s also important to note that, although the deleteOne() method is asynchronous, we handle it a bit differently. In other words, instead of passing a callback function, we use the then() method and pass a callback to that method. And once again, inside of that callback, we close the database connection.
Delete All Documents – Example # 6
In Example #6 we sort of kill two birds with one stone. We leverage the deleteMany() method and as you may have guessed, this method allows us to delete multiple documents in the database. Now, if we simply wanted to delete two or more documents, we would take an approach similar to the one in Example # 5, and pass an array of objects that contain ObjectIDs which match the documents we want to delete. In Example # 6, we wind up deleting every document in the database because we pass an empty object to the deleteMany() method. As with the deleteOne() method, deleteMany() is asynchronous, so we chain its then() method and pass a callback function to it. Inside of that callback function, we log our success and then close the database.
I’m hoping that this article has provided enough of a high-level understanding of MongDB’s basic operations to get you started. The examples are pretty simple, but they should be enough to help you do further digging around into CRUD operations. The main things to keep in mind are: most of the important methods that you will call are asynchronous, and the ObjectID is a critical component when you want to generate one or more matches with documents in the database.