
MongoDB е богата на документи ориентирана NoSQL база данни.
Ако сте напълно начинаещ в NoSQL, препоръчвам ви да разгледате набързо моята статия за NoSQL, публикувана по-рано.
Днес исках да споделя някои от основните неща за командите на MongoDB като заявки, филтриране на данни, изтриване, актуализиране и т.н.
Добре, стига беседите, да се захващаме за работа!
Конфигурация?
За да работите с MongoDB, първо трябва да инсталирате MongoDB на вашия компютър. За да направите това, посетете официалния център за изтегляне и изтеглете версията за вашата конкретна операционна система. Ето, използвах Windows.
След като изтеглите настройката на сървъра на общността MongoDB, ще преминете през инсталационен процес „следващ след следващ“. След като приключите, преминете към C устройството, в което сте инсталирали MongoDB. Отидете на програмните файлове и изберете директорията MongoDB.
C: -> Program Files -> MongoDB -> Server -> 4.0(version) -> bin
В директорията bin ще намерите интересна двойка изпълними файлове.
- монгод
- монго
Нека да поговорим за тези два файла.
mongod означава „Mongo Daemon“. mongod е фонов процес, използван от MongoDB. Основната цел на mongod е да управлява всички сървърни задачи на MongoDB. Например приемане на заявки, отговор на клиент и управление на паметта.
mongo е обвивка на командния ред, която може да взаимодейства с клиента (например системни администратори и разработчици).
Сега нека видим как можем да пуснем този сървър и да работи. За да направите това в Windows, първо трябва да създадете няколко директории във вашето устройство C. Отворете командния ред във вашето устройство C и направете следното:
C:\> mkdir data/dbC:\> cd dataC:\> mkdir db
Целта на тези директории е MongoDB изисква папка за съхраняване на всички данни. Пътят на директорията с данни на MongoDB по подразбиране е /data/db
на устройството. Следователно е необходимо да предоставяме тези директории по този начин.
Ако стартирате сървъра MongoDB без тези директории, вероятно ще видите следната грешка:

След като създадете тези два файла, преминете отново към папката bin, която имате във вашата директория mongodb, и отворете черупката си в нея. Изпълнете следната команда:
mongod
Voilà! Сега нашият сървър MongoDB работи и работи! ?
За да работим с този сървър, ни е необходим посредник. Затова отворете друг команден прозорец в папката за обвързване и изпълнете следната команда:
mongo
След като изпълните тази команда, отидете до черупката, която изпълнихме mongod команда (която е нашият сървър). В края ще видите съобщение „Приема се връзка“. Това означава, че нашата инсталация и конфигурация са успешни!
Просто изпълнете в монго черупката:
db

Настройване на променливи на околната среда
За да спестите време, можете да настроите променливите на вашата среда. В Windows това се прави, като следвате менютата по-долу:
Advanced System Settings -> Environment Variables -> Path(Under System Variables) -> Edit
Просто копирайте пътя на нашата папка bin и натиснете OK! В моя случай е такаC:\Program Files\MongoDB\Server\4.0\bin
Вече сте готови!
Работа с MongoDB
Има куп GUI (графичен потребителски интерфейс) за работа със сървър на MongoDB като MongoDB Compass, Studio 3T и т.н.
Те осигуряват графичен интерфейс, така че можете лесно да работите с вашата база данни и да изпълнявате заявки, вместо да използвате обвивка и да въвеждате заявки ръчно.
Но в тази статия ще използваме командния ред, за да си свършим работата.
Сега е време да се потопим в командите на MongoDB, които ще ви помогнат да използвате с бъдещите си проекти.
- Отворете командния ред и въведете
mongod
за да стартирате сървъра MongoDB.
2. Отворете друга обвивка и напишете mongo
за да се свържете със сървъра на база данни MongoDB.
1. Намиране на текущата база данни, в която се намирате
db

Тази команда ще покаже текущата база данни, в която се намирате. Това test
е първоначалната база данни, която идва по подразбиране.
2. Изброяване на бази данни
show databases

В момента имам четири бази данни. Те са: CrudDB
, admin
, config
и local
.
3. Отидете до определена база данни
use

Тук се преместих в local
базата данни. Можете да проверите това, ако опитате командатаdb
за да отпечатате текущото име на базата данни.
4. Създаване на база данни
С RDBMS (Релационни системи за управление на бази данни) имаме бази данни, таблици, редове и колони.
But in NoSQL databases, such as MongoDB, data is stored in BSON format (a binary version of JSON). They are stored in structures called “collections”.
In SQL databases, these are similar to Tables.


Alright, let’s talk about how we create a database in the mongo shell.
use
Wait, we had this command before! Why am I using it again?!
In MongoDB server, if your database is present already, using that command will navigate into your database.
But if the database is not present already, then MongoDB server is going to create the database for you. Then, it will navigate into it.
After creating a new database, running the show database
command will not show your newly created database. This is because, until it has any data (documents) in it, it is not going to show in your db list.
5. Creating a Collection
Navigate into your newly created database with the use
command.
Actually, there are two ways to create a collection. Let’s see both.
One way is to insert data into the collection:
db.myCollection.insert({"name": "john", "age" : 22, "location": "colombo"})
This is going to create your collection myCollection
even if the collection does not exist. Then it will insert a document with name
and age
. These are non-capped collections.
The second way is shown below:
2.1 Creating a Non-Capped Collection
db.createCollection("myCollection")
2.2 Creating a Capped Collection
db.createCollection("mySecondCollection", {capped : true, size : 2, max : 2})
In this way, you’re going to create a collection without inserting data.
A “capped collection” has a maximum document count that prevents overflowing documents.
In this example, I have enabled capping, by setting its value to true
.
The size : 2
means a limit of two megabytes, and max: 2
sets the maximum number of documents to two.
Now if you try to insert more than two documents to mySecondCollection
and use the find
command (which we will talk about soon), you’ll only see the most recently inserted documents. Keep in mind this doesn’t mean that the very first document has been deleted — it is just not showing.
6. Inserting Data
We can insert data to a new collection, or to a collection that has been created before.

There are three methods of inserting data.
insertOne()
is used to insert a single document only.insertMany()
is used to insert more than one document.insert()
is used to insert documents as many as you want.
Below are some examples:
- insertOne()
db.myCollection.insertOne( { "name": "navindu", "age": 22 } )
- insertMany()
db.myCollection.insertMany([ { "name": "navindu", "age": 22 }, { "name": "kavindu", "age": 20 }, { "name": "john doe", "age": 25, "location": "colombo" } ])
The insert()
method is similar to the insertMany()
method.
Also, notice we have inserted a new property called location
on the document for John Doe
. So if youusefind
, then you’ll see only forjohn doe
the location
property is attached.
This can be an advantage when it comes to NoSQL databases such as MongoDB. It allows for scalability.

7. Querying Data
Here’s how you can query all data from a collection:
db.myCollection.find()

If you want to see this data in a cleaner, way just add .pretty()
to the end of it. This will display document in pretty-printed JSON format.
db.myCollection.find().pretty()

Wait...In these examples did you just notice something like _id
? How did that get there?
Well, whenever you insert a document, MongoDB automatically adds an _id
field which uniquely identifies each document. If you do not want it to display, just simply run the following command
db.myCollection.find({}, _id: 0).pretty()
Next, we’ll look at filtering data.
If you want to display some specific document, you could specify a single detail of the document which you want to be displayed.
db.myCollection.find( { name: "john" } )

Let’s say you want only to display people whose age is less than 25. You can use $lt
to filter for this.
db.myCollection.find( { age : {$lt : 25} } )
Similarly, $gt
stands for greater than, $lte
is “less than or equal to”, $gte
is “greater than or equal to” and $ne
is “not equal”.
8. Updating documents
Let’s say you want to update someone’s address or age, how you could do it? Well, see the next example:
db.myCollection.update({age : 20}, {$set: {age: 23}})
The first argument is the field of which document you want to update. Here, I specify age
for the simplicity. In production environment, you could use something like the _id
field.
It is always better to use something like _id
to update a unique row. This is because multiple fields can have same age
and name
. Therefore, if you update a single row, it will affect all rows which have same name and age.

If you update a document this way with a new property, let’s say location
for example, the document will be updated with the new attribute. And if you do a find
, then the result will be:

If you need to remove a property from a single document, you could do something like this (let’s say you want age
to be gone):
db.myCollection.update({name: "navindu"}, {$unset: age});
9. Removing a document
As I have mentioned earlier, when you update or delete a document, you just need specify the _id
not just name
, age
, location
.
db.myCollection.remove({name: "navindu"});
10. Removing a collection
db.myCollection.remove({});
Note, this is not equal to the drop()
method. The difference is drop()
is used to remove all the documents inside a collection, but the remove()
method is used to delete all the documents along with the collection itself.
Logical Operators
MongoDB provides logical operators. The picture below summarizes the different types of logical operators.


Let’s say you want to display people whose age is less than 25, and also whose location is Colombo. What we could do?
We can use the $and
operator!
db.myCollection.find({$and:[{age : {$lt : 25}}, {location: "colombo"}]});
Last but not least, let’s talk aboutaggregation.
Aggregation
A quick reminder on what we learned about aggregation functions in SQL databases:

Simply put, aggregation groups values from multiple documents and summarizes them in some way.
Imagine if we had male and female students in a recordBook
collection and we want a total count on each of them. In order to get the sum of males and females, we could use the $group
aggregate function.
db.recordBook.aggregate([ { $group : {_id : "$gender", result: {$sum: 1}} } ]);

Wrapping up
So, we have discussed the basics of MongoDB that you might need in the future to build an application. I hope you enjoyed this article – thanks for reading!
If you have any queries regarding this tutorial, feel free to comment out in the comment section below or contact me on Facebook or Twitter or Instagram.
See you guys in the next article! ❤️ ✌?
Link to my previous article: NoSQL