Skip to content

Instantly share code, notes, and snippets.

@tomysmile
Last active August 4, 2021 10:56
Show Gist options
  • Save tomysmile/eb02e00bdc1fe0f40b678522b1bda2e0 to your computer and use it in GitHub Desktop.
Save tomysmile/eb02e00bdc1fe0f40b678522b1bda2e0 to your computer and use it in GitHub Desktop.
mongodb: basic operasional

Create Database

Show all database

Issue “show dbs” to display all available databases.

Connect to Server:

$ mongo --port 27017 -u [username] -p [password] --authenticationDatabase admin


Bash
MongoDB shell version: 1.8.1
connecting to: test
> show dbs
admin   0.03125GB
local   (empty)
Currently, only two databases are available – “admin” and “local“.

Define a database name

Issue “use new-databasename” to switch from default database to define database (even non-exists database name will work). However, MangoDB doesn’t create any database yet, until you save something inside.

> use my-new-db
switched to db my-new-db
> show dbs
admin   0.03125GB
local   (empty)

P.S Database “my-new-db” is not created yet.

Save It

Define a collection named “users“, and save a dummy document(value) inside.

> db.users.save( {username:"demo"} )
> db.users.find()
{ "_id" : ObjectId("4dbac7bfea37068bd0987573"), "username" : "demo" }
>
> show dbs
admin   0.03125GB
local   (empty)
my-new-db        0.03125GB

This says, “save this document (value) ‘{username:"demo"}‘ into the ‘user’ collection”. When this “save” operation is performed, MangoDB will create the “user” collection, and “my-new-db” database automatically.

Create user with 'Admin' access

use admin;

db.createUser({
  user: "admin",
  pwd: "[your-password]",
  roles: [ "root" ]
  }
);

Create User with 'ReadWrite' access

use [your-database];

db.createUser({
  "user" : "[your-username]",
  "pwd" : "[your-password]",
  roles : [
      {
          "role" : "readWrite",
          "db" : "[your-database]"
      }
  ]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment