MongoDB¶
MongoDB is a NoSQL document storage as such it is different to Relational Databases (RDBs) like MySQL or postgreSQL.
The data within mongo is stored as documents in JSON format. They are organized in collections, which is the same as tables in a relational database.
Installation¶
Under debian it is in the default package repository:
apt-get install -y mongodb
This should also install the mongodb-server
and mongodb-clients
on your system.
Shell¶
To manage the documents you may use the contained shell:
mongo [<dbname>]
This will give you an interactive shell to administrate. It's a JavaScript based shell.
Commands¶
In the following table you find some common command examples.
Command | Usage |
---|---|
db |
show current db name |
db.<collection>.find().pretty() |
list all documents and pretty print |
db.<collection>.insert(<json>) |
insert document |
GUI¶
There are a lot of GUIs available, a lot of them professional. I found MongoDB Compass a usable thing:
It provides users with a graphical view of their MongoDB schema without the need of query language. It also analyses documents and displays rich structures inside this intuitive GUI.
Features:
- The tool allows to explore data visually
- MongoDB Compass analyzes documents and displays rich structures within one collection using Run ad-hoc queries in seconds
- Supports quick insight into server status and query performance
- Allows to view query performance
- A better approach to CRUD makes it easier to interact
- It helps users to take decisions about indexing, document validation, and more
- No need to write command line
Management¶
Database¶
To create a new database you only have to access it:
> use mydb
switched to db mydb
And to get the name of the current database use the db
command.
Users¶
Using db.createUser()
new users can be added:
> db.createUser({
... user: "alex",
... pwd: "test123",
... roles: ["readWrite", "dbAdmin"]
... });
Successfully added user: { "user" : "alex", "roles" : [ "readWrite", "dbAdmin" ] }
Collections¶
To create a collection, use the db.createCollection()
method. It takes one parameter: the name of the collection.
> db.createCollection("persons");
{ "ok" : 1 }
The success message will be ok with the count of affected items (or created collections, in this case).