MongoDB 101: For beginners (part?2)
Before reading this tutorial on how to manipulate data using MongoDB CRUD operations, I recommend that you first read (part 1) to understand what is MongoDB, if you already did then that’s awesome ?? by now you should know what is MongoDB, and what are its building blocks! So let’s install MongoDB and get those hands dirty with some real code, are you ready? ??
Environment Setup
I’ll walk you through installing MongoDB and Mongosh shell on Windows, If you use macOS feel free to check the Offical tutorial for installing MongoDB on macOS.
How to setup MongoDB on?Windows
1- Install the MongoDB 5.0 Community?.msi installer for windows from MongoDB Download Center
2- Navigate to the Downloads directory where you downloaded the MongoDB?.msi installer and double-click on it to run it.
3- Choose the recommended Complete installation option, and follow the installation wizard. For more details about the wizard installation options check the Official installation Manual.
4- Install the Mongosh?.msi installer from Mongo Download Center, then follow the prompt. After the installation is done, open the mongosh terminal and hit enter to use the default database (mongodb://localhost/). If this is the output you see on the screen CONGRATULATIONS you did it ??
1- Create or Insert Operations
All write operations on a single document are atomic, meaning that the operation either fully completes or aborts and doesn’t write at all.
To insert one document into a collection we use db.collection.insertOne(), and to insert many documents at once we use db.collection.insertMany()?.
insertOne()
For example, to insert one document into a collection called user, open your mongosh shell and write the following command:
> db.user.insertOne({
first_name: "Nicholas",
last_name: "Coleman",
email: "[email protected]",
gender: "Female",
age: 22,
})
-------------------------------------------------------
{
acknowledged: true,
insertedId: ObjectId("623e24234a@bb8d32fa961cc")
}
If the document doesn’t already exist, the?insertOne() operation creates it and returns its ObjectId in the?insertedId?field.
insertMany()
For example, if you have many users you want to insert at once in the?user?collection, you better use?insertMany()?to make one database call instead of multiple calls. You simply pass a list of documents within the parentheses of the?insertMany() function separated by a comma as follows:
> db.user.insertMany([
... {
... first_name: "Nicholas".
... last_name: "Coleman"
... email: "[email protected]",
... gender: "Female",
... age: 22,
... },
... {
... first_name: "Zoe",
... last_name: "Paige",
... email: "zoe. [email protected]",
... gender: "male",
... age: 27,
... }
... ])
----------------------------------------------------
{
acknowledged: true,
insertedIds: {
'0': ObjectId("623e2bd24a@bb8d32fa961do"),
'1': ObjectId("623e2bd24a0bb8d32fa961d1")
}
}
2- Read operations
find()
To retrieve all data in a collection, we use?db.collection.find()?operation without passing any arguments, below is a simple example.
> db.user.find()
---------------------------------------------------
[
{
_id: ObjectId("623e2ce74a@bb8d32fa961d2"),
first_name: 'Nicholas',
last_name: 'Coleman',
email: '[email protected]',
gender: 'Female',
age: 22
},
{
_id: ObjectId("623e2ce74a@bb8d32fa961d3"),
first_name: 'Zoe',
last_name: 'Paige',
email: '[email protected]'.
gender: 'male',
age: 27
}
]
With MongoDB read operations you can customize your query by applying query filters/criteria, that allow you to retrieve a desired subsection of the records. You can also limit how many results to return and which fields to return. The MongoDB documentation contains more information on the available?query filters or criteria.
Let's see an example of retrieving only female users whose ages are greater than or equal to 20, and we only want to return the first_name, gender, and age fields.
Well, we have two conditions here (user’s gender = female) AND (user’s age ≥ 20). We translate this in MongoDB using the?$and?(it takes an array of condition objects),?$gte?(i.e. greater than or equal), and a projection to return only specific fields (set a field to 1 to include it, or to 0 to exclude it).
领英推荐
> db.user.find(
... {
..... $and: [ {gender: "female"}, {age: {$gte: 20}} ]
..... },
... { first_name: 1, gender: 1, age: 1 }
... )
---------------------------------------------------------
[
{
_id: ObjectId("623e2fcd4a0bb8d32fa961d4"),
first_name: 'Serrah',
gender: 'female',
age: 22
},
{
_id: ObjectId("623e2fcd4a0bb8d32fa961d5"),
first_name: 'emme',
gender: 'female',
age: 27
}
]
findOne()
If we want to retrieve only one document that matches query criteria, we will use db.collection.findOne()?instead of?db.collection.find()?and apply any?query filters or criteria?as discussed previously.
A most common example is looking up a user by their ObjectId.
> db.user.findOne(ObjectId("623e2fcd4a0bb8d32fa961d5"))
-------------------------------------------------------
{
_id: ObjectId("623e2fcd4a0bb8d32fa961d5"),
first_name: 'emme',
last_name: 'kal',
email: '[email protected]',
gender: 'female',
age: 27
}
Or finding a user by their name. For instacne, find the first record whose first name?is “Nicholas”.
> db.user.findOne({first_name: "Nicholas"})
------------------------------------------------
{
_id: ObjectId("623e2ce74a0bb8d32fa961d2"),
first_name: 'Nicholas',
last_name: 'Coleman',
email: '[email protected]',
gender: 'Female',
age: 22
}
3- Update Operations
Just as the read operations, update operations also take query filtering arguments, with the addition of an?update operation?and some other optional arguments. One thing to note here is that updates are permanent and can’t be rolled back, this applies to delete operations as well, so be careful. There are three update functions in MongoDB that I will explain next.
updateOne()
For example, let's say we want to update Nicholas’s age from 22 to 23. We first pass in the update filter which is Nicholas’s unique?_id. Then, we use the “$set” key and provide the new age to the age field as a value. This method will update the first record that matches the provided filter as we can see in?matchedCountand?modifiedCountfields.
> db.user.updateOne(
{ _id: ObjectId("623e2ce74a0bb8d32fa961d2") },
{ $set: {age: 23} }
)
--------------------------------------------------
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
updateMany()
Just as we did with inserting many documents, updating multiple documents is also possible. We do this by passing in a list of all documents along with the update operation, to the updateMany() function.
Do you remember the other optional parameter that I mentioned earlier? yes, the upsert.
What is Upsert?
Upsert is basically an update or insert operation. In MongoDB, upsert is an optional boolean parameter in all update operations. When we set it to true, MongoDB will create a new document from the fields in the update filter only if no documents match the filter. This is particularly useful when you aren’t sure if the records exist, so you aren’t sure you should call insert alone or update alone. However, keep in mind the performance decreases when using upsert, due to the cost of scanning the collection looking for the document to update or insert.
replaceOne()
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.
4- Delete Operations
Ok, let’s delete Nicholas ??. We only need to pass a query filter to the?deleteOne()?function as in the below example. Also, just as we did with?insertMany()?and?updateMany()?we can also?deleteMany().
> db.user.deleteOne({ _id: ObjectId("623e2ce74a0bb8d32fa961d2")})
-----------------------------------------------------------------{
acknowledged: true,
deletedCount: 1
}
And that’s it! congratulations on learning data manipulation in MongoDB. And for more information and example feel free to check?MongoDB documentation.