banner



How To Start Mongodb Service In Windows 10

How to get started with MongoDB in 10 minutes

past Navindu Jayatilake

How to get started with MongoDB in 10 minutes

DCrUp7WMs8e6ije4HWFDwTIO1PORbljQW3H7

MongoDB is a rich certificate-oriented NoSQL database.

If you are a complete beginner to NoSQL, I recommend you to have a quick await at my NoSQL article published previously.

Today, I wanted to share some of the bones stuff about MongoDB commands such every bit querying, filtering data, deleting, updating and so on.

Okay, enough of the talk, let'due south go to work!

Configuration ?

In lodge to work with MongoDB, outset you lot need to install MongoDB on your estimator. To practice this, visit the official download middle and download the version for your specific OS. Here, I've used Windows.

After downloading MongoDB community server setup, you lot'll go through a 'side by side later next' installation process. In one case done, head over to the C bulldoze in which you accept installed MongoDB. Go to program files and select the MongoDB directory.

                C: -> Program Files -> MongoDB -> Server -> iv.0(version) -> bin              

In the bin directory, you'll find an interesting couple of executable files.

  • mongod
  • mongo

Allow'south talk about these two files.

mongod stands for "Mongo Daemon". mongod is a groundwork process used by MongoDB. The principal purpose of mongod is to manage all the MongoDB server tasks. For instance, accepting requests, responding to customer, and memory management.

mongo is a command line beat out that tin can interact with the client (for instance, arrangement administrators and developers).

At present let's see how nosotros can get this server up and running. To practise that on Windows, first you need to create a couple of directories in your C drive. Open up up your control prompt within your C drive and do the following:

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

The purpose of these directories is MongoDB requires a folder to store all data. MongoDB's default data directory path is /data/db on the drive. Therefore, information technology is necessary that we provide those directories like then.

If yous start the MongoDB server without those directories, you'll probably see this following mistake:

r04FRmRGqKUaclGh4ZDo3YsMwOlXMVm2T3bJ
trying to start mongodb server without \information\db directories

After creating those two files, head over again to the bin folder y'all accept in your mongodb directory and open upward your shell inside information technology. Run the following command:

                mongod              

VoilĂ ! Now our MongoDB server is upwardly and running! ?

In club to piece of work with this server, nosotros need a mediator. Then open up another command window inside the bind folder and run the following control:

                mongo              

After running this command, navigate to the shell which we ran mongod command (which is our server). You'll run across a 'connection accepted' message at the terminate. That means our installation and configuration is successful!

Just just run in the mongo trounce:

                db              
TK2JGg4JXAj0eG9JBzl89ABEF3JuKAwnw2dx
initially you have a db chosen 'test'

Setting up Environment Variables

To save fourth dimension, yous tin can gear up your environment variables. In Windows, this is washed by post-obit the menus below:

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

Simply copy the path of our bin folder and hit OK! In my case it'due south C:\Programme Files\MongoDB\Server\4.0\bin

Now you're all set!

Working with MongoDB

In that location's a agglomeration of GUIs (Graphical User Interface) to work with MongoDB server such as MongoDB Compass, Studio 3T and so on.

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

Only in this article nosotros'll exist using command prompt to exercise our piece of work.

Now it'southward time for us to dive into MongoDB commands that'll assist yous to employ with your future projects.

  1. Open up up your command prompt and type mongod to kickoff the MongoDB server.

2. Open up another beat and type mongo to connect to MongoDB database server.

ane. Finding the current database y'all're in

                db              
o6puQoPSpGCW8-AgizHzAv3Qpywtzsgwd26N

This command will bear witness the current database you lot are in. test is the initial database that comes past default.

2. Listing databases

                show databases              
Q-G8NzP5OAXh0Y3OfdOtqFxlFG-tLErPlPSi

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

3. Become to a particular database

                use <your_db_name>              
UIRueBuX-r6nRXA-qd6Uv95IBd0UbhVvMZtZ

Here I've moved to the local database. Y'all can cheque this if yous try the control db to print out the current database name.

4. Creating a Database

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

Only in NoSQL databases, such as MongoDB, data is stored in BSON format (a binary version of JSON). They are stored in structures chosen "collections".

In SQL databases, these are like to Tables.

e7ygVKXaPcqcqCyvurAeUzAbmmREoA6p72V2
oxeGaPqbZ2pmmZx3WcDo8CXIL4J09PbecBWW
SQL terms and NoSQL terms by Victoria Malaya

Alright, let's talk about how we create a database in the mongo shell.

                use <your_db_name>              

Wait, we had this command earlier! Why am I using information technology again?!

In MongoDB server, if your database is present already, using that control will navigate into your database.

Merely if the database is non present already, and so MongoDB server is going to create the database for y'all. And then, it will navigate into it.

Subsequently creating a new database, running the show database control volition not show your newly created database. This is because, until it has any data (documents) in it, it is non going to evidence in your db listing.

v. Creating a Drove

Navigate into your newly created database with the use command.

Actually, at that place are two ways to create a collection. Let'southward see both.

One mode is to insert information into the collection:

                db.myCollection.insert({"proper name": "john", "age" : 22, "location": "colombo"})              

This is going to create your drove myCollection fifty-fifty if the collection does not exist. And then it will insert a document with proper noun and age. These are non-capped collections.

The second fashion is shown below:

2.1 Creating a Non-Capped Drove

                db.createCollection("myCollection")              

2.2 Creating a Capped Drove

                db.createCollection("mySecondCollection", {capped : true, size : ii, max : 2})              

In this fashion, y'all're going to create a collection without inserting information.

A "capped collection" has a maximum certificate count that prevents overflowing documents.

In this instance, I have enabled capping, by setting its value to true.

The size : 2 ways a limit of two megabytes, and max: ii sets the maximum number of documents to ii.

Now if you try to insert more than than two documents to mySecondCollection and employ the find control (which nosotros will talk about shortly), you'll only see the most recently inserted documents. Continue in mind this doesn't hateful that the very beginning certificate has been deleted — it is merely not showing.

half dozen. Inserting Data

We can insert data to a new collection, or to a collection that has been created before.

uO4agHbI85kMJrQmF1L9pMmhn0WcgngmoPsI
ways data can be stored in a JSON

There are 3 methods of inserting data.

  1. insertOne() is used to insert a unmarried certificate just.
  2. insertMany() is used to insert more than one certificate.
  3. insert() is used to insert documents as many as you desire.

Below are some examples:

  • insertOne()
                db.myCollection.insertOne(   {     "name": "navindu",      "age": 22   } )              
  • insertMany()
                db.myCollection.insertMany([   {     "proper name": "navindu",      "age": 22   },   {     "name": "kavindu",      "historic period": twenty   },    {     "name": "john doe",      "age": 25,     "location": "colombo"   } ])              

The insert() method is similar to the insertMany() method.

Also, notice we have inserted a new holding called location on the document for John Doe . Then if you lot utilise find , then yous'll see only for john doe the location property is attached.

This tin be an advantage when it comes to NoSQL databases such as MongoDB. Information technology allows for scalability.

QyCgwWUHWoporNunUvoRgdVry-x0QyA8qSxd
Successfully inserted data

7. Querying Data

Here'due south how you lot tin can query all data from a collection:

                db.myCollection.notice()              
rzcViLqDrTy5gqSFoY6n3N7dciNxFTY62eRL
issue

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

                db.myCollection.find().pretty()              
gMIbpNqjr9jmJ3YVDZruX1skX0PCvSruuZWB
result

Look...In these examples did you just discover something like _id? How did that become at that place?

Well, whenever y'all insert a document, MongoDB automatically adds an _id field which uniquely identifies each document. If y'all do not want it to display, just simply run the following command

                db.myCollection.find({}, _id: 0).pretty()              

Next, nosotros'll look at filtering information.

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.detect(   {     proper name: "john"   } )              
TiBBNNp9gmxtPXaHd5BSZ7MkSrv1JkRzkMI1
event

Permit's say you want just to display people whose age is less than 25. You tin can use $lt to filter for this.

                db.myCollection.find(   {     historic period : {$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 lot could do it? Well, run into the side by side example:

                db.myCollection.update({historic period : twenty}, {$set: {age: 23}})              

The first statement is the field of which document you want to update. Here, I specify age for the simplicity. In product environment, y'all could use something similar the _id field.

Information technology is always amend to apply something similar _id to update a unique row. This is because multiple fields tin can accept same age and name. Therefore, if y'all update a single row, it volition affect all rows which have aforementioned name and age.

qQH53vM6-peOzS-z9k5YjMoS9R2z1APJrXvB
consequence

If you update a certificate this way with a new property, let'southward say location for case, the document will be updated with the new attribute. And if you do a discover, then the outcome volition be:

YqJpPAw7d5NPSTzStCevUmgoDTm6FkgPLZ-7
result

If you need to remove a property from a unmarried certificate, you could exercise something like this (let's say you want age to be gone):

                db.myCollection.update({name: "navindu"}, {$unset: historic period});              

9. Removing a document

Equally I have mentioned earlier, when you update or delete a document, yous just demand specify the _id non simply proper noun, age, location.

                db.myCollection.remove({name: "navindu"});              

x. 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 within 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.

xO27jGeclafiAUt0a0VYRifhDpISvZcIkhRD
VsHbrchxUETWqCFhZc6QvmSPUdrbfOHYEH3L
reference: MongoDB transmission

Allow'southward say y'all want to brandish people whose age is less than 25, and besides whose location is Colombo. What we could do?

We can apply the $and operator!

                db.myCollection.discover({$and:[{age : {$lt : 25}}, {location: "colombo"}]});              

Final but not least, let'southward talk about aggregation.

Assemblage

A quick reminder on what we learned about aggregation functions in SQL databases:

JHcuA7YLBiFiCBn1QiOS8NYCUELbGg-LKDSN
assemblage functions in SQL databases. ref : Tutorial Gateway

Merely 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 become the sum of males and females, nosotros could use the $group amass office.

                db.recordBook.aggregate([   {     $group : {_id : "$gender", upshot: {$sum: ane}}   }   ]);              
NeK7Wx3lQ1AaUhGD1VERqmaluAl9qrsXpDMs
issue

Wrapping upwardly

So, we have discussed the basics of MongoDB that yous might need in the futurity to build an awarding. I promise you enjoyed this article – thanks for reading!

If you have whatsoever queries regarding this tutorial, feel free to comment out in the comment department below or contact me on Facebook or Twitter or Instagram.

See y'all guys in the next article! ❤️ ✌?

Link to my previous commodity: NoSQL


Learn to code for free. freeCodeCamp's open source curriculum has helped more than than 40,000 people get jobs equally developers. Get started

Source: https://www.freecodecamp.org/news/learn-mongodb-a4ce205e7739/

Posted by: havilandfert1948.blogspot.com

0 Response to "How To Start Mongodb Service In Windows 10"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel