• Home
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • Maven
  • About
Big Data | Install and configure MongoDB (4.2)
  1. References
  2. Install MongoDB
  3. Start MongoDB
  4. Uninstall MongoDB
  5. How to create users in MongoDB?
  6. MongoDB "admin" database
  7. How to use collections?
  8. Some common "mongo" commands
  9. How to execute "mongo" commands from Linux shell?
  10. How to allow remote connections to MongoDB?
  11. Cannot install MongoDB on Ubuntu?

  1. References
    See this page for more details on how to install MongoDB:
    https://docs.mongodb.com/manual/installation/
  2. Install MongoDB
    $ sudo apt update
    $ sudo apt install -y mongodb-org

    Enable mongod server service:
    $ sudo systemctl enable mongod.service
    $ sudo systemctl start mongod.service

    Check installation:
    $ mongo --version
    MongoDB shell version v4.2.0
    git version: a4b751dcf51dd249c5865812b390cfd1c0129c30
    OpenSSL version: OpenSSL 1.1.1  11 Sep 2018
    allocator: tcmalloc
    modules: none
    build environment:
        distmod: ubuntu1804
        distarch: x86_64
        target_arch: x86_64

    Configuration files:
    • Binary file: /usr/bin/mongod

    • Configuration file: /etc/mongod.conf

    • DB path: /var/lib/mongodb/

    • Log file: /var/log/mongodb/mongod.log
  3. Start MongoDB
    Start MongoDB as a service:
    $ sudo service mongod start

    Start MongoDB as a process using "config" paramter:
    $ nohup /usr/bin/mongod --config /etc/mongod.conf &

    Start MongoDB as a process using "dbpath" paramter:
    $ nohup /usr/bin/mongod --dbpath /var/lib/mongodb &

    Verify MongoDB status:
    $ sudo service mongod status

    Verify MongoDB process:
    $ ps -ef | grep mongodb
    mongodb   1517   /usr/bin/mongod --config /etc/mongod.conf

    List active connections:
    $ lsof -i | grep mongo

    $ netstat -l | grep 27017
    tcp        0      0 localhost:27017         0.0.0.0:*               LISTEN
    unix  2      [ ACC ]     STREAM     LISTENING     1391442  /tmp/mongodb-27017.sock

    Stop MongoDB:
    $ sudo service mongod stop
  4. Uninstall MongoDB
    Uninstall MongoDB:
    $ sudo service mongod stop
    
    $ sudo apt purge mongodb-org*
    $ sudo apt autoremove
    
    $ sudo rm -r /var/log/mongodb
    $ sudo rm -r /var/lib/mongodb
  5. How to create users in MongoDB?
    Create a user/password on a specific database:
    $ mongo

    If you don't connect to a specific database, the user will be created on the "test" database:
    > use mymdb

    Create the user:
    > db.createUser(
      {
        user: "user1",
        pwd: "pwd1",
        roles: [
          {
            role: "dbOwner",
            db: "mymdb"
          }
        ]
      }
    )
    Successfully added user: {
      "user" : "user1",
      "roles" : [
        {
          "role" : "dbOwner",
           "db" : "mymdb"
        }
      ]
    }
    

    Verify user creation:
    > use mymdb
    switched to db mymdb
    > db.auth("user1", "pwd1")
    1

    Test user connection:
    $ mongo -u user1 -p pwd1 mymdb
    > db.getUser("user1")
    {
      "_id" : "mymdb.user1",
      "userId" : UUID("59ace827-0b71-4674-a2cd-82ad6fd004d1"),
      "user" : "user1",
      "db" : "mymdb",
      "roles" : [
        {
          "role" : "dbOwner",
          "db" : "mymdb"
        }
      ],
      "mechanisms" : [
        "SCRAM-SHA-1",
        "SCRAM-SHA-256"
      ]
    }

    List all users of a database:
    > use mymdb
    > db.getUsers()

    Delete a user:
    > use mymdb
    > db.dropUser('user1')
  6. MongoDB "admin" database
    $ mongo

    > use admin
    switched to db admin

    > show collections
    system.users
    system.version

    > db.system.users.find()
    {
      "_id": "mymdb.user1",
      "userId": UUID("b79c29e7-2ec8-41fa-924b-b08b6c33549d"),
      "user": "user1",
      "db": "mymdb",
      "credentials": {
        "SCRAM-SHA-1": {
          "iterationCount": 10000,
          "salt": "vb85F7h2TomgGGm7mw3ksw==",
          "storedKey": "rQ0GGHBN0affRBFGe3Wvm4Yrgfg=",
          "serverKey": "yKnztyYNJW15tH/nBte/h01tD0A="
        },
        "SCRAM-SHA-256": {
          "iterationCount": 15000,
          "salt": "yPFiaRmV9ffKw7iZU+ROP/uLVb1w9/X1lwrF4A==",
          "storedKey": "5Mlt6bA9p6dP+xch5hI6NItes0fmyHF9lIiYu5euXgs=",
          "serverKey": "a1Hwo5Cyc8E6vQGDpqxR1wRLuSZ6qEU3VCeZAh8QH3M="
        }
      },
      "roles": [
        {
          "role": "dbOwner",
          "db": "mymdb"
        }
      ]
    }

    > db.system.version.find()
    { "_id" : "featureCompatibilityVersion", "version" : "4.2" }
  7. How to use collections?
    $ mongo

    > use mymdb

    > db.createCollection("mycollection")

    > show collections
    mycollection

    > db.mycollection.find({},{_id:1})

    > db.mycollection.find()
  8. Some common "mongo" commands
    > db.getMongo()

    > show users
    > db.getUsers()
    > db.getUser("user1")

    > show roles

    > db.dropUser("user1")

    > show databases
    > show dbs
    > db.getMongo().getDBNames()
    > db.adminCommand("listDatabases")

    > use mymdb
    > db.getName()

    > db.dropDatabase()

    > show collections
    > db.getCollectionNames()
    > db.createCollection("mycollection")

    > show tables

    > db.mycollection.find()
    > db.mycollection.findOne()
    > db.mycollection.find().limit(10)
    > db.mycollection.count();

    > db.mycollection.dataSize()
    > db.mycollection.storageSize()
    > db.mycollection.totalIndexSize()
    > db.mycollection.totalSize()

    > db.printCollectionStats()
    > db.mycollection.stats()
  9. How to execute "mongo" commands from Linux shell?
    List databases:
    $ mongo --quiet --eval  "printjson(db.adminCommand('listDatabases'))"
    {
      "databases" : [
        {
          "name" : "admin",
          "sizeOnDisk" : 176128,
          "empty" : false
        },
        {
          "name" : "config",
          "sizeOnDisk" : 110592,
          "empty" : false
        },
        {
          "name" : "local",
          "sizeOnDisk" : 73728,
          "empty" : false
        },
        {
          "name" : "mymdb",
          "sizeOnDisk" : 8192,
          "empty" : false
        }
      ],
      "totalSize" : 368640,
      "ok" : 1
    }

    List collections names of a specific database:
    $ mongo -u user1 -p pwd1 mymdb --quiet --eval  "printjson(db.getCollectionNames())"
    [ "mycollection" ]
  10. How to allow remote connections to MongoDB?
    Configuration file: /etc/mongod.conf
    # network interfaces
    net:
      port: 27017
      bindIp: 127.0.0.1,192.168.2.33  # Comment to listen on all interfaces.
    
    security:
      authorization: enabled

    Test connection:
    $ mongo --host localhost --port 27017 -u user1 -p pwd1 mymdb
  11. Cannot install MongoDB on Ubuntu?
    Remove mongodb-org package: Uninstall MongoDB

    Remove the existing mongodb.list:
    $ sudo rm /etc/apt/sources.list.d/mongodb*.list

    Create the MongoDB repository list file:
    $ echo "deb [arch=amd64] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list

    If you execute the command "apt update" you might get the following error:
    W: GPG error: https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 Release:
    The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 4B7C549A058F8B6B
    E: The repository 'https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 Release' is not signed.
    N: Updating from such a repository can't be done securely, and is therefore disabled by default.

    So first, you need to add the MongoDB key:
    $ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 4B7C549A058F8B6B
    Executing: /tmp/apt-key-gpghome.r2EHiLZD0B/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv 4B7C549A058F8B6B
    gpg: key 4B7C549A058F8B6B: public key "MongoDB 4.2 Release Signing Key <packaging@mongodb.com>" imported
    gpg: Total number processed: 1
    gpg:               imported: 1

    Install MongoDB:
    $ sudo apt update
    $ sudo apt install -y mongodb-org

    You can find the MongoDB puclic key ("4B7C549A058F8B6B") by visiting the Ubuntu key server http://keyserver.ubuntu.com
    • Enter the "OpenPGPkeyserver": MongoDB
    • Click "Search Key".
    • In the search result page, find the version "4.2" and look for the last up-to-date key.
© 2025  mtitek