My MongoDB notes

From Got Opinion Wiki
Jump to navigation Jump to search

MongoDB is a general purpose, document-based, distributed database built for modern application developers and for the cloud era.

Ubuntu

install

Install and run MongoDB Community Edition on Ubuntu 18.04 LTS

The site has excellent documentation so I am simply providing overview of steps.

  1. Import the public key used by the package management system.
  2. Create a list file for MongoDB.
  3. Reload local package database.
  4. Install the MongoDB packages.

Run MongoDB Community Edition

  1. Start MongoDB with sudo service mongod start
  2. Verify that MongoDB has started successfully with sudo grep port /var/log/mongodb/mongod.log or sudo service mongod status
  3. Stop MongoDB with sudo service mongod stop
  4. Restart MongoDB with sudo service mongod restart
  5. Begin using MongoDB shell with mongo

Verify MongoDB starts on Ubuntu 18.04 start up (MongoDB Community Edition default install does not start on Ubuntu 18.04 startup)

$ sudo systemctl list-unit-files | grep mongod
mongod.service                             enabled  <--- If this value is not enabled, run below command to activate.

Configure MongoDB to start on Ubuntu 18.04 start up

$ sudo systemctl enable mongod.service
Created symlink /etc/systemd/system/multi-user.target.wants/mongod.service → /lib/systemd/system/mongod.service.

mongo shell

mongo shell manual

Running mongo at shell $ mongo

Exit mongo shell > exit

Display mongo shell help > help

add MongoDB user and enable remote management access

User documentation

Steps to setup first user and enable access control resource

create user administrator (sample file, use your own user and pwd values)

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

Enable MongoDB instance to start with access control enabled by editing MongoDB config $ sudo vi /etc/mongod.conf

Enable security.authorization configuration option

security:
  authorization: enabled

Bind IP address that enables remote connection to MongoDB (optional step)

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,192.168.1.109 <-- An IP address on your server that you want MongoDB to listen for TCP connections.

Shutdown instance within mongo shell db.adminCommand( { shutdown: 1 } )

After restart attempt MongoDB instance failed to start.

The MongoDB log had this:

$ sudo tail /var/log/mongodb/mongod.log    
2019-08-11T15:41:04.940-0500 I CONTROL  [initandlisten]     distarch: x86_64
2019-08-11T15:41:04.940-0500 I CONTROL  [initandlisten]     target_arch: x86_64
2019-08-11T15:41:04.940-0500 I CONTROL  [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1,192.168.1.109", port: 27017 }, processManagement: { timeZoneInfo: "/usr/share/zoneinfo" }, security: { authorization: "enabled" }, storage: { dbPath: "/var/lib/mongodb", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log" } }
2019-08-11T15:41:04.940-0500 E NETWORK  [initandlisten] Failed to unlink socket file /tmp/mongodb-27017.sock Unknown error
2019-08-11T15:41:04.940-0500 F -        [initandlisten] Fatal Assertion 40486 at src/mongo/transport/transport_layer_asio.cpp 685
2019-08-11T15:41:04.940-0500 F -        [initandlisten] 

***aborting after fassert() failure

Root owns file and we want mongodb user to own file

$ ls -l /tmp/mongodb-27017.sock
srwx------ 1 root root 0 Aug 11 15:31 /tmp/mongodb-27017.sock

The fix is to delete file so it can be recreated with correct permissions.

$ sudo rm /tmp/mongodb-27017.sock

Verify that TCP socket is closed or you will get Failed to set up listener: SocketException: Address already in use upon start up

$ netstat -an | grep 27017
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN

TCP port 27017 in use so you have to close the port $ sudo kill $(sudo lsof -t -i:27017)

Verify TCP port in use (should get no output) $ netstat -an | grep 27017

Upon start attempt received another failure due to file permissions.

Verify that mongodb user and group own all files and directories $ ls -la /var/lib/mongodb

If you see root on any file or directory except '..' then change permissions using $ sudo chown -R mongodb:mongodb /var/lib/mongodb

Now start MongoDB instance and verify access control and TCP port in bound to bindIp values from above.

$ sudo systemctl start mongod          

$ sudo systemctl status mongod
● mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2019-08-11 16:14:13 CDT; 4s ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 19662 (mongod)
   CGroup: /system.slice/mongod.service
           └─19662 /usr/bin/mongod --config /etc/mongod.conf

Aug 11 16:14:13 hammerhead systemd[1]: Started MongoDB Database Server.

$ netstat -an | grep 27017                 
tcp        0      0 192.168.1.109:27017     0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN     
unix  2      [ ACC ]     STREAM     LISTENING     13117024 /tmp/mongodb-27017.sock

Connect and authenticate as user administrator

Authenticate during connection to mongo mongo --port 27017 -u "myUserAdmin" --authenticationDatabase "admin" -p

or

$ mongo --port 27017
> use admin
> db.auth("myUserAdmin", "abc123" )

Create additional users (example)

After being authenticated...

> use test
switched to db test
> db.createUser(
...   {
...     user: "testdbuser",
...     pwd: "xyz123",
...     roles: [ { role: "readWrite", db: "test" },
...              { role: "read", db: "reporting" } ]
...   }
... )
Successfully added user: {
        "user" : "testdbuser",
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "test"
                },
                {
                        "role" : "read",
                        "db" : "reporting"
                }
        ]
}

grant additional roles to user

db.grantRolesToUser(username, roles, writeConcern)

Manual references

connection string page describes the URI formats for defining connections between applications and MongoDB instances in the official MongoDB drivers

Windows 10 (dev environment)

Download MongoDB Community Edition zip package

Extract downloaded file and rename to root directory to mongodb.

Move mongodb directory to user profile. On my Windows 10 dev machine the absolute path is C:\Users\anon\mongodb.

Create directory in same profile that will hold mongodb collections called mongodb-data. The absolute path is C:\Users\anon\mongodb-db.

To run MongoDB open shell in C:\Users\anon\mongodb\bin directory and type .\mongod.exe --dbpath=\Users\anon\mongodb-data\

MongoDB GUI

Robo 3T (formerly Robomongo) is the free lightweight GUI for MongoDB enthusiasts.

MongoDB drivers

MongoDB ecosystem drivers

MongoDB Node.js drivers

MongoDB Node.js API docs

My Ubuntu notes | My Windows 10 notes