Download and run MongoDB

You can download MongoDB Community edition from the Mongo DB Download Center. You will be provided with a *.msi installation package. At the point of writing this 3.6.5 the current stable version.

If you choose the default installation path, your MongoDB binaries are to be found at C:\Program Files\MongoDB\Server\3.6\bin.

Follow this manual to install the mongodb server as a windows service.

Alternatively, if you rather to start the server manually – instead of using a windows service – you can simple run the mongod binary in a cmd console.

run mongod from a cmd window

As you see in the image above mongodb expects to find a C:\data\db folder. This is mongodb´s default data directory. Since the installer has not created it, we can can create it manually running from the command line this commands:

md c:\data
md c:\data\db

Also, you can change the location of the data directory by editing accordingly mongodb´s configuration file.

Once the server is running you can access the mongo shell by running the mongo command from a cmd

If you add the mongo path to the system path variable, you will have easier access to the mongo shell.

path_mongodb_binaries

Using the Mongo Shell

Now we have mongodb installed is time to see a few shell commands:

List databases

show dbs

Switch to the current DB. Attention: this command will create the database, if it does not exist!

use database

Display collections in the database:

show collections

Let´s see also some operations over collections. Imagine we have a collections named ShoesCatalog.

Let’s create our ShoesCatalog collection, and insert a document in the collection:

db.ShoesCatalog.insertOne( { size: 42, brand:"CoolSportShoes", price:100 } );

Bulk insert of multiple elements:

db.ShoesCatalog.insertMany( [{ size: 38, brand:"X-Sandals", price:50 },{ size: 36, brand:"CoolSportShoes", price:90 } ]);

List all documents in our ShoesCatalog collection:

db.ShoesCatalog.find()

Return first element found of a collection:

db.ShoesCatalog.findOne()

Format the output in the console so that it is easier to read:

db.ShoesCatalog.find().pretty

Of course, you can search elements in a collection filtering by a field:

db.ShoesCatalog.findOne({ size: 42})
db.ShoesCatalog.find({ size: 42})

Get number of elements in a collection:

db.ShoesCatalog.count();

Drop collection:

db.ShoesCatalog.drop();

Drop a database:

use "name_database"
db.dropDatabase();
Advertisements