MongoDB

MongoDB basics - Create, Show and Drop Collections

MongoDB basics - Create, Show and Drop Collections
MongoDB is a NoSQL database. This means that unlike relational databases there's no set in stone schema with various row and columns or fields with well-defined data types. Analogue to traditional SQL database tables, MongoDB has collections. Where there were once rows in a SQL table, MongoDB has documents. Data is queried across all collections and documents using key-value pairs, which you will soon see.

The utility of MongoDB is its ease of use, scalability and the JSON like syntax with which the stored data is represented. On the other hand, if you wish to do crazy operations on your datasets like JOINs you may find MongoDB cumbersome and traditional SQL databases are better suited for that.

In any case, this article would not presume any familiarity with databases whatsoever. We will just assume that you have MongoDB installed on your server/desktop (it is available on Windows, Mac and Linux). With that installed we will create our sample database and see MongoDB in action.

Prerequisites

  1. MongoDB installation. You can follow the official documentation to install your current Operating System. OR
  2. Optionally, you can sign up for MongoDB atlas. They offer a free tier with 512MB of persistent storage. Perfect environment for experimentation or small projects.
  3. If you wish to not install any software whatsoever, you can visit Katacoda and use their web-based interface as an ephemeral sandboxed environment.

Getting Started

Assuming you have MongoDB server installed and a shell connected to the server we can start exploring a few features of it. But first a few terminologies - A mongodb server has a list of databases dbs in it. Each database can have multiple collections in it.

So for example, a University can have a personnel database which can then have various collections for different departments like one collection for Mathematics, one for Biology and so on.

Each collection can then have a document inside it, a document would have an individual staff personnel's details listed in it. As mentioned before, the stored data is represented in a JSON-like fashion and we can query different values using the keys they are paired with.

Create Database

Creating a database happens implicitly when you try to use a database. In this example, if you are in Mongo shell and you type in:

> use testDb

MongoDB first checks to see if you have a database with the name testdb, if not, then it creates a new one for you to use and the Mongo Shell switches to testdb. This means that every collection and document created, updated or read would be from this database, unless explicitly specified otherwise.

You can use the command > db to print what database you are in right now and use the command > show dbs  to list all of the databases available and created.

> db
testDb
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
mydb    0.000GB

You may want to leave the admin, config databases as it is used by Mongo for administrative purposes.

Create Collection

To create a collection, first ensure that you are in the appropriate database where you intend on creating the collection. You can now create a collection in two different way:

1.   Explicitly Creating a Collection:

Using the command:

> db.createCollection("testCollection1");
"ok" : 1

This created a collection named testCollection1.

2.   Inserting a Document to a new collection

Alternatively, you can easily try to insert a document in a collection that doesn't exist. Mongo will create a collection for you. Please note that while this is a convenience in terms of programmatically creating collections, if you are using Mongo shell and make a typo somewhere while trying to insert a document, the document may end up in a new database unbeknownst to you.
The syntax is: db.collection_name.insert(document);
Here db is literally the string db, collection

For example, to create a collection testCollection2 in testDb database use the following command:

> db.testCollection2.insert(
name: "John",
key: “value”
age: 25
);

Here, the document part is represented my the following JSON string:


name: "John",
key: “value”
age: 25

These are the key-value pairs typical of a JSON string. The name is key and “John” is value. You can have multiple documents in this collection with the key name and a different value for name, say, Jane.

To list all the collections inside a given database, use the command:

> show collections
testCollection1
testCollection2

You can see both the collections are now created. We have also inadvertently learned how to add a new document to a collection.

Show

We have been using show keyword quite a lot to list the collections and databases. Just to recap this a bit, these were the commands:

> show dbs
> show collections

These along with the command db to print the current database can come in quite handy while interacting with the Mongo shell.

Drop Collections and Drop Databses

The keyword drop is something we haven't come across so far. It is used to remove collections or even entire databases from your mongo server. The following syntax walks you through the process:

1.  Dropping Collection

Let's get rid of the collection testCollection2 we created earilier:

> db.testCollection2.drop()

You can use the show collections command to verify that this indeed worked. There will be one database less than we had previously, I will let you guess which one will be missing.

2.  Drop Database

Before you blindly run the command to drop the database, make absolutely sure that you are in the right database. Or else you might end up losing valuable data stored elsewhere. We will be dropping the database testDb that we created earlier, let's make sure that that's where we are:

> db
testDb
> db.dropDatabase();

The latter command drops the database, as you can tell from the name.

Conclusion

MongoDB has gain popularity along with the Node.js project. They both share a kind of symbiosis which enabled each to be a success. JSON like representation, scalability and an ease and dynamic way of creating documents has earned MongoDB quite the fame.

If you are looking for database technology for a quick weekend project or even for some serious data heavy-lifting, MongoDB is an option you should give some serious consideration.

Linux'ta Oyun Nasıl Geliştirilir
On yıl önce, pek çok Linux kullanıcısı en sevdikleri işletim sisteminin bir gün ticari video oyunları için popüler bir oyun platformu olacağını tahmin...
Open Source Ports of Commercial Game Engines
Free, open source and cross-platform game engine recreations can be used to play old as well as some of the fairly recent game titles. This article wi...
Linux için En İyi Komut Satırı Oyunları
Komut satırı, Linux kullanırken yalnızca en büyük müttefikiniz değil, aynı zamanda eğlence kaynağı da olabilir, çünkü onu özel bir grafik kartı gerekt...