Intro
We're going to start talking about how to actually use MongoDB to build and manipulate databases. In this discussion, we are going to be using the MongoDB Shell to build and manipulate our database, and in the next discussion, we'll show you how to use MongoDB Compass.
We are going to be creating a database for an Animal Shelter. This database could hold information on different pets such as dogs and cats, and also perhaps, people that may be looking for pets. But, the first thing we do is to create the new database.
Once you have a database created, we will create what are called Collections to store and reference the data. Think of collections as basically different categories of data that are stored in the database.
And finally, once you have a database, with at least one Collection, you then create what are called Documents. Documents are, in the end, the actual data being stored.
More information on all of the CRUD (Create/Read/Update/Delete) operations can be found on the MongoDB Docs Page.
MongoDB Shell
Create the Database
To create a new database in the MongoDB Shell:
- Open your Terminal App of choice.
- Start MongoDB by entering mongosh
Once you are IN the MongoDB Shell, you can use:
- show dbs, to show all of the current databases
- show collections, to show all of the collections within a database (if you are IN a database)
And now to create the new database for our Animal Shelter, by entering:
*note: the use keyword will switch to a db if it exists, or it will create a new db if it does not.
Once the db is created, the Mongo Shell should switch to the "animalShelter" db (your cursor should change from test>, to animalShelter>). If it does not, or at anytime you want to switch to that db you just created, by using the use keyword:
Create a Collection
To create a Collection in the MongoDB Shell, you have two options:
- 1. You can enter db.createCollection("collectionName")
- which will create an empty collection with no data.
- or,
- 2. You can enter db.collectionName.insertOne( {collectionData} )
- which will create a new collection and populate it with the data.
*note: when you enter db.collectionName.insertOne(), if that collection does not exist, MongoDB will create it and insert the collection data. If the collection already exists, it will simply add the data to the existing collection.
We are going to use option 2 which will create the Collection and populate it with it's first document. The Collection will be called dogs, and our Document will be populated with data for our first dog, like so:
- db.dogs.insertOne( { name: "Chico", age: 10, breed: "Pit Bull", catFriendly: true } )
So we have created our first Collection and added our first Document which holds the data for a dog named "Chico."
Also, according to the MongoDB docs, to insert one "collection" item you use db.insertOne(), and to enter multiple collection items, you use db.insertMany(). However, the db.insertOne() method works for either single or multiple entries, and here's why. If you are going to add "multiple" collections of data at once, just add them as multiple objects of an array.
As you can see from our example db.dogs.insertOne( { chicoData } ), our collection data is entered as an object, so to add multiple items, you could use db.dogs.insertOne( [ { chicoData }, { dog2Data } ] ) and just create an array structure, like so:
Now you've probably noticed is that the collections look an awful lot like json objects, but they are not. They are actually "JavaScript" objects, and there is a distinction. For one thing, when using the MongoDB Shell, the key names are not enclosed in parenthesis.
Also, when using the shell, once you hit enter to create or add data to a collection, Mongo returns a promise:
- {
- acknowledged: true,
- insertedId: ObjectId('67f5908cf09a1c0894b71236')
- }
This shows that the Document was created and assigned a unique ID number. And now, if we enter show collections, we see dogs has been created. We can also use db.dogs.find() to display all of the entries in this collection, and we get:
- [
- {
- _id: ObjectId('67f5908cf09a1c0894b71236'),
- name: 'Chico',
- age: 10,
- breed: 'Pit Bull',
- catFriendly: true
- }
- ]
One quick note about the ID numbers. You can generate your own ID's if you wish. Mongo will only generate an ID if one does not already exist.
Read from a Collection
So we now know how to Create a database, and next we're going to learn how to Read some data from a database. Remember that we are working within the CRUD framework which stands for Create/Read/Update/Delete.
So the basic command to read from a database is:
so if we enter:
it will list all of the Documents in the dogs Collection. But we can enter in our own "search" criteria into the find field to narrow down our Read results by adding an object like so:
- db.dogs.find( { breed: "Pit" } )
This will list all of the results with a "breed" of "Pit". A couple of notes here. The search is case sensitive. Also, this type of search will return ALL of the results that match the search criteria. There is another method called:
that we can use to return the first instance of the search criteria.
Update a Collection
The next part of the CRUD process is to Update our Documents. With Mongo, there are basically three ways to update. We can:
- collection.updateOne()
- collection.updateMany()
- collection.replaceOne()
and they're pretty self explanatory. We can either update one document, many documents, or we can replace an entire document. If we replace a document, the document will still retain the unique ID that was assigned to it at creation.
To update we use the $set keyword. We need to provide two values. The first value provides the "Read" criteria to find the Document(s) we want to Update. The second value contains the $set keyword followed by the updated value. Each one of these individual values is entered as an object. The basic syntax is:
- db.databaseName.updateOne( { find criteria }, { $set: { new criteria } } )
notice the structure for the separate objects here. Let's update our "Chico" document in our dogs collection to demonstrate. Right now we have:
- {
- _id: ObjectId('67f5908cf09a1c0894b71236'),
- name: 'Chico',
- age: 10,
- breed: 'Pit Bull',
- catFriendly: true
- }
We're going to change his age from 10 to 11:
- db.dogs.updateOne( { name: "Chico" }, { $set: { age: 11 } } )
and Mongo returns:
- { acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
and if we look at the "Chico" document, we now have:
- {
- _id: ObjectId('67f5908cf09a1c0894b71236'),
- name: 'Chico',
- age: 11,
- breed: 'Pit Bull',
- catFriendly: true
- }
Now updateMany() works exactly the same way, but it will update every document that matches the search criteria. And replaceOne() will also work, essentially the same way, but it will replace everything in the document, with the exception of the unique ID, with the new data you enter for value two. It will retain the original unique ID set at creation, but it will replace everything else.
One last thing about $set. There are many other update operators that Mongo uses for many different purposes. $set is the one we will use most. More information on these update operators can be found here.
Delete a Collection
We've been following along with our CRUD utilization, and so far we've learned how to Create, Read, and Update. And lastly we are going to see how to Delete. Now Delete works very similar to Update in that we can deleteOne(), or we can deleteMany(). Here's the basic syntax:
- db.collectionName.deleteOne( { findCriteria } )
- db.collectionName.deleteMany( { findCriteria } )
So we use the findCriteria to find the document(s) we wish to delete from the collectionName. For example, we have a Document in our dogs Collection that refers to our dog "Chico". We could Delete this Document like so:
- db.dogs.deleteOne( { name: "Chico" } )
so our Collection we want to delete from is dogs, and our findCriteria is name = "Chico". So if we run this it will delete the document for "Chico".
We can also deleteMany(), just as easy. We have a property in the dogs collection for each document, catFriendly. If we wanted to delete all of the dogs that are not cat friendly, we course use deleteMany() and set our findCriteria to "catFriendly: false", like so:
- db.dogs.deleteMany( { catFriendly: false } )
and that will delete ALL of the Documents in the dogs Collection that match "catFriendly = false". Another important point here is that we are not limited to one single findCriteria. We could run a Delete with several findCriteria, like so:
- db.dogs.deleteMany( { catFriendly: false, age: 5 } )
so it will look for ALL dogs that are NOT catFriendly, AND are 5 years old.
And lastly, you can delete every document in a Collection, by using deleteMany(), and omitting the findCriteria, like so:
- db.collectionName.deleteMany( { } )
So, deleteMany() with no findCriteria, will delete EVERY Document, in the specified Collection.