MongoDB

From wiki.techunit.org
Jump to: navigation, search


Use on Debian 7+

Install

  1. Import public key: sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
  2. Create the list file: echo "deb http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
  3. Update the local package database: sudo apt-get update
  4. Install the latest stable version of MongoDB: sudo apt-get install -y mongodb-org

Uninstall

  1. Stop MongoDB's service: sudo service mongod stop
  2. Remove all packages: sudo apt-get purge mongodb-org*
  3. Remove logs: sudo rm -r /var/log/mongodb
  4. Remove databases: sudo rm -r /var/lib/mongodb

Shell

  • Start MongoDB's service: sudo service mongod start
  • Check MongoDB's service status in file /var/log/mongodb/mongod.log and check line: [initandlisten] waiting for connections on port <Port number from /etc/mongod.conf>
  • Stop MongoDB's service: sudo service mongod stop
  • Restart MongoDB's service: sudo service mongod restart
  • Connect to MongoDB: mongo --port 27017 -u <user> -p <password> --authenticationDatabase admin

Directories

  • Logs path: /var/log/mongodb
  • Databases path: /var/lib/mongodb
  • Configuration file path: /etc/mongod.conf

Administration

Manage connection

  • Allow all remote connections (not recommend)

In configuration file, comment out the lines : net: port: 27017 bindIp: 127.0.0.1

Commands

Basics

  • Connect to database: use <dbName>

Administration

  • Add user: db.createUser({ user: "<userName>", pwd: "<password>", roles: [{ role: "<roleName>", db: "<dbName>" }, ...] })
  • Create a role
    • You must have createRole & grantRole or you can have userAdmin or userAdminAnyDatabase
    • You have to use admin database for transverse permissions
  • Create an index on a field: db.<collName>.createIndex( { <fieldName>: "<fieldType>" } )

Queries