Sådan kommer du i gang med MongoDB på 10 minutter

MongoDB er en rig dokumentorienteret NoSQL-database.

Hvis du er en helt nybegynder til NoSQL, anbefaler jeg dig at kigge hurtigt på min NoSQL-artikel, der tidligere er offentliggjort.

I dag ville jeg dele nogle af de grundlæggende ting om MongoDB-kommandoer som forespørgsel, filtrering af data, sletning, opdatering og så videre.

Okay, nok af samtalen, lad os komme på arbejde!

Konfiguration?

For at arbejde med MongoDB skal du først installere MongoDB på din computer. For at gøre dette skal du besøge det officielle downloadcenter og downloade versionen til dit specifikke operativsystem. Her har jeg brugt Windows.

Efter download af MongoDB-community-serveropsætningen gennemgår du en 'næste efter næste' installationsproces. Når du er færdig, skal du gå over til C-drevet, hvor du har installeret MongoDB. Gå til programfiler, og vælg MongoDB-biblioteket.

C: -> Program Files -> MongoDB -> Server -> 4.0(version) -> bin

I papirkurven finder du et interessant par eksekverbare filer.

  • mongod
  • mongo

Lad os tale om disse to filer.

Mongod står for "Mongo Daemon". mongod er en baggrundsproces, der bruges af MongoDB. Hovedformålet med mongod er at styre alle MongoDB-serveropgaverne. For eksempel at acceptere anmodninger, svare på klient og hukommelsesstyring.

mongo er en kommandolinjeskal, der kan interagere med klienten (for eksempel systemadministratorer og udviklere).

Lad os nu se, hvordan vi kan få denne server i gang. For at gøre det på Windows skal du først oprette et par mapper i dit C-drev. Åbn din kommandoprompt inde i dit C-drev, og gør følgende:

C:\> mkdir data/dbC:\> cd dataC:\> mkdir db

Formålet med disse mapper er MongoDB kræver en mappe til at gemme alle data. MongoDBs standarddatakatalogsti er /data/dbpå drevet. Derfor er det nødvendigt, at vi leverer disse mapper sådan.

Hvis du starter MongoDB-serveren uden disse mapper, vil du sandsynligvis se denne følgende fejl:

Når du har oprettet disse to filer, skal du gå tilbage til den bin-mappe, du har i din mongodb-mappe, og åbne din skal inde i den. Kør følgende kommando:

mongod

Voilà! Nu er vores MongoDB-server oppe og køre! ?

For at arbejde med denne server har vi brug for en mediator. Så åbn et andet kommandovindue inde i bindmappen, og kør følgende kommando:

mongo

Efter at have kørt denne kommando, naviger til den shell, som vi kørte mongod-kommandoen (som er vores server). Du får vist en meddelelse om "forbindelse accepteret" i slutningen. Det betyder, at vores installation og konfiguration er vellykket!

Bare løb bare i mongoskallen:

db

Opsætning af miljøvariabler

For at spare tid kan du indstille dine miljøvariabler. I Windows gøres dette ved at følge nedenstående menuer:

Advanced System Settings -> Environment Variables -> Path(Under System Variables) -> Edit

Du skal blot kopiere stien til vores bin-mappe og trykke på OK! I mit tilfælde er detC:\Program Files\MongoDB\Server\4.0\bin

Nu er du klar!

Arbejder med MongoDB

Der er en masse GUI'er (grafisk brugergrænseflade) til at arbejde med MongoDB-server som MongoDB Compass, Studio 3T og så videre.

They provide a graphical interface so you can easily work with your database and perform queries instead of using a shell and typing queries manually.

But in this article we’ll be using command prompt to do our work.

Now it’s time for us to dive into MongoDB commands that’ll help you to use with your future projects.

  1. Open up your command prompt and type mongodto start the MongoDB server.

2. Open up another shell and type mongoto connect to MongoDB database server.

1. Finding the current database you’re in

db

This command will show the current database you are in. test is the initial database that comes by default.

2. Listing databases

show databases

I currently have four databases. They are: CrudDB, admin, config and local.

3. Go to a particular database

use 

Here I’ve moved to the local database. You can check this if you try the command dbto print out the current database name.

4. Creating a Database

With RDBMS (Relational Database Management Systems) we have Databases, Tables, Rows and Columns.

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 usecommand.

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 myCollectioneven if the collection does not exist. Then it will insert a document with nameand 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.

  1. insertOne() is used to insert a single document only.
  2. insertMany() is used to insert more than one document.
  3. 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 locationon the document for John Doe. So if youusefind, then you’ll see only forjohn doe the locationproperty 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 ageto 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 $andoperator!

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:

Kort sagt, aggregering grupperer værdier fra flere dokumenter og opsummerer dem på en eller anden måde.

Forestil dig, hvis vi havde mandlige og kvindelige studerende i en recordBooksamling, og vi vil have en total beregning på hver af dem. For at få summen af ​​mænd og kvinder kunne vi bruge den $groupsamlede funktion.

db.recordBook.aggregate([ { $group : {_id : "$gender", result: {$sum: 1}} } ]);

Afslutter

Så vi har diskuteret det grundlæggende i MongoDB, som du muligvis har brug for i fremtiden for at oprette en applikation. Jeg håber du nød denne artikel - tak for læsningen!

Hvis du har spørgsmål vedrørende denne tutorial, er du velkommen til at kommentere i kommentarfeltet nedenfor eller kontakte mig på Facebook eller Twitter eller Instagram.

Se jer i den næste artikel! ❤️ ✌?

Link til min tidligere artikel: NoSQL