MongoDB – TecAdmin https://tecadmin.net How to guide for System Administrator's and Developers Thu, 22 Dec 2022 08:46:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 How to Use LIKE Statement in MongoDB https://tecadmin.net/using-sql-like-statement-in-mongodb/ https://tecadmin.net/using-sql-like-statement-in-mongodb/#respond Sat, 26 Sep 2020 17:49:20 +0000 https://tecadmin.net/?p=22697 MongoDB is an powerful Nosql database server. MongoDB uses JSON-like documents with optional schemas to store data. Its always a critical task for a develop to organize data. As it plays most important role in the application performance. In Mongodb, you can use queries similar to SQL LIKE statement to fetch data. For the examples [...]

The post How to Use LIKE Statement in MongoDB appeared first on TecAdmin.

]]>
MongoDB is an powerful Nosql database server. MongoDB uses JSON-like documents with optional schemas to store data.

Its always a critical task for a develop to organize data. As it plays most important role in the application performance. In Mongodb, you can use queries similar to SQL LIKE statement to fetch data.

For the examples used in this tutorial, we uses some dummy data as below. You can also create a database and execute below commands to insert dummy data.

db.colors.insert({ "id": 100, "color": "Pink"})
db.colors.insert({ "id": 101, "color": "Purple"})
db.colors.insert({ "id": 102, "color": "Black"})
db.colors.insert({ "id": 103, "color": "Blue"})

Using .find()

The Mongodb find() command is used to search documents from a collection. This function provides flexible options to search documents.

The default find() function retrieve all the documents in a collection. It also allows you to query a collection of documents, by passing a few simple parameters, and return a cursor.

A simple example of the .find() method look like below:

> db.colors.find()
{ "_id" : ObjectId("5f697e4ccc528930cde49f53"), "id" : 100, "color" : "Pink" }
{ "_id" : ObjectId("5f697e4fcc528930cde49f54"), "id" : 101, "color" : "Purple" }
{ "_id" : ObjectId("5f697e52cc528930cde49f55"), "id" : 102, "color" : "Black" }
{ "_id" : ObjectId("5f697e55cc528930cde49f56"), "id" : 103, "color" : "Blue" }

The above returns all the documents in a collection. But this is very uncommon on production requirements. You always required some filtered results from a database.

For example, fetch all documents contains “color: Pink”. Execute query like:

>  db.colors.find({color: "Pink"})

Mongo match exact string

Using .find() as SQL LIKE Statement

You can use regular expression for searching documents in monogdb. This will be similar to LIKE statements in SQL queries.

  1. Search String Anywhere – To search all document where color name have “Pink” anywhere in string. The second statement searches for all documents where color have "Bl" in there name.
    ### SQL Statement 
    select * from colors where color LIKE "%Pink%"
    
    ### Mongodb Statement 
    db.colors.find(color: "/Pink/")
    

    Mongodb match find with substring

  2. Search String Start With – This will match all the string start with P characters. The carrot “^” symbol is used for start with.
    ### SQL Statement 
    select * from colors where color LIKE "P%"
    
    ### Mongodb Statement 
    db.colors.find(color: "/^P/")
    

  3. Search String End With – The dollar “$” symbol is used to match string ends with specific characters. The below example matches all strings ends with “k” character.
    ### SQL Statement 
    select * from colors where color LIKE "%k"
    
    ### Mongodb Statement 
    db.colors.find(color: "/k$/")
    

  4. Search String In Any Case – The default find method search with case-sensitive. You can instruct find command to match characters in any case with “i” option as used in below example.
    ### SQL Statement 
    select * from colors where color LIKE BINARY "pink"
    
    ### Mongodb Statement 
    db.colors.find(color: "/pink/i")
    

  5. Conclusion

    In this tutorial, you have learned to to search database similar to SQL LIKE statements in Mongodb.

    The post How to Use LIKE Statement in MongoDB appeared first on TecAdmin.

    ]]> https://tecadmin.net/using-sql-like-statement-in-mongodb/feed/ 0 How to Enable Authentication in MongoDB https://tecadmin.net/enable-authentication-in-mongodb/ https://tecadmin.net/enable-authentication-in-mongodb/#respond Sun, 05 Jul 2020 04:21:02 +0000 https://tecadmin.net/?p=21919 Having the ability to authenticate users with your database is an important security feature. This is especially true when that database is storing sensitive information, such as user accounts for a website or company data. With authentication enabled on your MongoDB instance, you can set specific rules about what user accounts are permitted to do [...]

    The post How to Enable Authentication in MongoDB appeared first on TecAdmin.

    ]]>
    Having the ability to authenticate users with your database is an important security feature. This is especially true when that database is storing sensitive information, such as user accounts for a website or company data.

    With authentication enabled on your MongoDB instance, you can set specific rules about what user accounts are permitted to do and what sort of access they have. This also means that you can also lock down certain features so that only authorized users have access to them.

    In this article, we will show you how to enable authentication in MongoDB so that only authorized users can access the database and its contents.

    Create an Admin User

    We will first create a user to manage all users and databases, and then we will create a MongoDB database owner with reading and write privileges on one database instance.

    To manage all users and databases, create an admin user on your MongoDB server. Using Mongo shell, switch to the admin database and create a user.

    use admin 
    
    db.createUser({
       "user":"admin",
       "pwd":"admin_password",
       "roles":[
          {
             "role":"root",
             "db":"admin"
          }
       ]
    }) 
    

    Verify the authentication, run command on Mongo shell:

    db.auth("admin", "admin_password") 
    

    The result “1” is for successful authentication.

    Create Database Specific User

    Now, set up a user for your application’s database. Use the “use” command to select your database, and then create a user with the following commands. You must change the database name, username, and password to the ones listed below.

    use mydb 
    
    db.createUser({
       "user":"db_user",
       "pwd":"your_password",
       "roles":[
          {
             "role":"dbOwner",
             "db":"mydb"
          }
       ]
    }) 
    

    Verify the authentication, run command on Mongo shell:

    db.auth("db_user", "your_password") 
    

    The result “1” is for successful authentication.

    Enabling Authentication on MongoDB

    You have just created a user for your database. Now, flip the authentication switch to enforce login. To enforce authentication on your MongoDB server, edit /etc/mongod.conf in your preferred text editor.

    sudo vim /etc/mongod.conf 
    

    Add/Edit the below lines to the configuration file

    security:
          authorization: enabled
    

    Save your file and close.

    Then restart the MongoDB instance to apply the changes.

    sudo systemctl restart mongod 
    

    All done!

    Conclusion

    You have secured your MongoDB server by enabling proper authentication on databases. MongoDB will reject all requests without authentication. Its also recommended to restrict Mongodb port 27017 via a firewall, whether it is provided by the cloud hosting or the system’s inbuild firewall.

    The post How to Enable Authentication in MongoDB appeared first on TecAdmin.

    ]]>
    https://tecadmin.net/enable-authentication-in-mongodb/feed/ 0
    A Shell Script to Backup MongoDB Database https://tecadmin.net/shell-script-backup-mongodb-database/ https://tecadmin.net/shell-script-backup-mongodb-database/#comments Sun, 21 Jun 2020 02:42:29 +0000 https://tecadmin.net/?p=21810 Did you know that MongoDB databases have a built-in backup mechanism that is accessible via shell or the mongod process? The mongod process automatically takes a snapshot every time a database transitions to another state. These different states are: starting, stopping, upgrading, and recovering after a crash. However, these snapshots won’t be enough in case [...]

    The post A Shell Script to Backup MongoDB Database appeared first on TecAdmin.

    ]]>
    Did you know that MongoDB databases have a built-in backup mechanism that is accessible via shell or the mongod process? The mongod process automatically takes a snapshot every time a database transitions to another state. These different states are: starting, stopping, upgrading, and recovering after a crash. However, these snapshots won’t be enough in case of catastrophic failures such as disk corruption or natural disaster. To protect your valuable data from such threats, it is advisable to implement an automated backup strategy for your MongoDB databases.

    In this article, we will discuss how to create automated backups for your MongoDB databases using a simple Shell script.

    Shell Script for MongoDB Backup

    The shell script for MongoDB database backup is available on Github. You can use the below link to get access of the shell script.

    https://github.com/tecrahul/shell-scripts/blob/master/backup-mongo.sh

    Alternatively, You can copy the below script and save it on your Linux system.

    #!/bin/bash
     
    ######################################################################
    ##
    ##   MongoDB Database Backup Script 
    ##   Written By: Rahul Kumar
    ##   URL: https://tecadmin.net/shell-script-backup-mongodb-database/
    ##   Update on: June 20, 2020
    ##
    ######################################################################
     
    export PATH=/bin:/usr/bin:/usr/local/bin
    TODAY=`date +"%d%b%Y"`
     
    ######################################################################
    ######################################################################
     
    DB_BACKUP_PATH='/backup/mongo'
    MONGO_HOST='localhost'
    MONGO_PORT='27017'
    
    # If MongoDB is protected with a username password.
    # Set AUTH_ENABLED to 1 
    # and add MONGO_USER and MONGO_PASSWD values correctly
    
    AUTH_ENABLED=0
    MONGO_USER=''
    MONGO_PASSWD=''
    
    
    # Set DATABASE_NAMES to "ALL" to backup all databases.
    # or specify databases names separated with space to backup 
    # specific databases only.
    
    DATABASE_NAMES='ALL'
    #DATABASE_NAMES='mydb db2 newdb'
    
    ## Number of days to keep a local backup copy
    BACKUP_RETAIN_DAYS=30   
     
    ######################################################################
    ######################################################################
     
    mkdir -p ${DB_BACKUP_PATH}/${TODAY}
    
    AUTH_PARAM=""
    
    if [ ${AUTH_ENABLED} -eq 1 ]; then
    	AUTH_PARAM=" --username ${MONGO_USER} --password ${MONGO_PASSWD} "
    fi
    
    if [ ${DATABASE_NAMES} = "ALL" ]; then
    	echo "You have choose to backup all databases"
    	mongodump --host ${MONGO_HOST} --port ${MONGO_PORT} ${AUTH_PARAM} --out ${DB_BACKUP_PATH}/${TODAY}/
    else
    	echo "Running backup for selected databases"
    	for DB_NAME in ${DATABASE_NAMES}
    	do
    		mongodump --host ${MONGO_HOST} --port ${MONGO_PORT} --db ${DB_NAME} ${AUTH_PARAM} --out ${DB_BACKUP_PATH}/${TODAY}/
    	done
    fi
    
     
    ######## Remove backups older than {BACKUP_RETAIN_DAYS} days  ########
     
    DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`
     
    if [ ! -z ${DB_BACKUP_PATH} ]; then
          cd ${DB_BACKUP_PATH}
          if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
                rm -rf ${DBDELDATE}
          fi
    fi
     
    ######################### End of script ##############################

    Run Script Manually

    Save the above script in a file with .sh extension. I want to save all the backups under /the backup directory. So placed the shell script in the same directory. Then set the execute permission on the script.

    chmod +x /backup/backup-mongo.sh 
    

    Run the shell script as below:

    bash /backup/backup-mongo.sh 
    

    Schedule MongoDB Backup Script

    You can easily schedule this script under crontab to backup databases regularly. To edit the crontab, run crontab -e command and append the below code:

    ## Backup database daily at 02:00 AM
    0 2 * * * /backup/mongo-backup.sh

    Wrap Up

    In this tutorial, we have discussed a shell script that helps to backup MongoDB databases manually. Also, you can schedule scripts to backup databases on regular basis.

    The post A Shell Script to Backup MongoDB Database appeared first on TecAdmin.

    ]]>
    https://tecadmin.net/shell-script-backup-mongodb-database/feed/ 2
    How To Install MongoDB in Fedora 36/35 https://tecadmin.net/install-mongodb-on-fedora/ https://tecadmin.net/install-mongodb-on-fedora/#comments Sat, 07 Jul 2018 11:35:37 +0000 https://tecadmin.net/?p=16458 MongoDB is a fully flexible index support and rich queries database. It is classified as a NoSQL database program, which uses JSON-like documents with optional schemas. Similar to the relational database system, the MongoDB database also supports joins in queries. MongoDB has released a new stable version 4.4 with lots of major enhancements. This tutorial [...]

    The post How To Install MongoDB in Fedora 36/35 appeared first on TecAdmin.

    ]]>
    MongoDB is a fully flexible index support and rich queries database. It is classified as a NoSQL database program, which uses JSON-like documents with optional schemas. Similar to the relational database system, the MongoDB database also supports joins in queries.

    MongoDB has released a new stable version 4.4 with lots of major enhancements. This tutorial will help you to install MongoDB 4.4 on Fedora Linux systems.

    Step 1 – Configure Repository

    The MongoDB official team provides an Yum repository for installing MongoDB on a Fedora system. Create a new configuration file with Mongodb yum repository. Edit a file in a editor:

    sudo vi /etc/yum.repos.d/mongodb.repo 
    

    Add the below content

    [Mongodb]
    name=MongoDB Repository
    baseurl=https://repo.mongodb.org/yum/redhat/8/mongodb-org/4.4/x86_64/
    gpgcheck=1
    enabled=1
    gpgkey=https://www.mongodb.org/static/pgp/server-4.4.asc
    

    Save the file and close it.

    Step 2 – Install MongoDB on Fedora

    Let’s use the DNF package manager to install the MongoDB server on the Fedora system. This will also install all required dependencies to your system.

    To install MongoDB on Fedora, type:

    sudo dnf install mongodb-org mongodb-org-server 
    

    How to Install MongoDB in Fedora Linux

    Step 3 – Start MongoDB Service

    MongoDB server has been installed on your Fedora systems. Now enable the MongoDB systemd service and start it.

    sudo systemctl enable mongod.service 
    sudo systemctl start mongod.service 
    

    Once the service is started, check the current status with the following command.

    sudo systemctl status mongod.service 
    

    How to Install MongoDB in Fedora Linux

    Step 4 – Connect to MongoDB Shell

    As you have completed the MongoDB installation on your Fedora Linux system. First of all, verify the installed MongoDB version on your system with the following command.

    mongod --version 
    
    Output:
    db version v4.4.4 Build Info: { "version": "4.4.4", "gitVersion": "8db30a63db1a9d84bdcad0c83369623f708e0397", "openSSLVersion": "OpenSSL 1.1.1k FIPS 25 Mar 2021", "modules": [], "allocator": "tcmalloc", "environment": { "distmod": "rhel80", "distarch": "x86_64", "target_arch": "x86_64" } }

    Now, connect to the MongoDB shell using the mongo command-line utility. Also, execute some test commands for checking proper working.

    mongo 
    
    > use mydb;
    
    > db.test.save({ tecadmin: 1001 })
    
    > db.test.find()
    
    { "_id" : ObjectId("60d472f31f5ba51557c8b066"), "tecadmin" : 1001 }
    

    Conclusion

    Congratulation’s You have successfully installed mongodb server on Fedora system. For practice only you may use MongoDB browser shell.

    References:
    http://docs.mongodb.org/manual/installation/

    The post How To Install MongoDB in Fedora 36/35 appeared first on TecAdmin.

    ]]>
    https://tecadmin.net/install-mongodb-on-fedora/feed/ 6
    How to Install MongoDB 4.2 on Debian 10/9/8 https://tecadmin.net/install-mongodb-server-on-debian/ https://tecadmin.net/install-mongodb-server-on-debian/#comments Thu, 05 Oct 2017 15:57:46 +0000 https://tecadmin.net/?p=13574 MongoDB is a full flexible index support and rich queries database. It is a NoSQL database. MongoDB provides large media storage with GridFS. Click here for more details about this version of MongoDB. Use this tutorial to install MongoDB server 4.2 on Debian 10, Debian 9 Stretch and Debian 8 Jessie systems. Prerequisites You must [...]

    The post How to Install MongoDB 4.2 on Debian 10/9/8 appeared first on TecAdmin.

    ]]>
    MongoDB is a full flexible index support and rich queries database. It is a NoSQL database. MongoDB provides large media storage with GridFS. Click here for more details about this version of MongoDB. Use this tutorial to install MongoDB server 4.2 on Debian 10, Debian 9 Stretch and Debian 8 Jessie systems.

    Prerequisites

    You must have shell access with sudo privileded account to your Debian system.

    Login to your system and open a shell.

    Step 1 – Installing MongoDB on Debian

    You need to execute following commands step by step to install MongoDB on Debian Linux systems.

    1. First of all, import MongoDB public GPG key in your system
      sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 656408E390CFB1F5
      
    2. Next, add MongoDB apt repository url to your Debian system.
      echo "deb http://repo.mongodb.org/apt/debian "$(lsb_release -sc)"/mongodb-org/4.2 main" | sudo tee /etc/apt/sources.list.d/mongo.list 
      
    3. Now, install the MongoDB server packages on Debian system.
      sudo apt update 
      sudo apt install mongodb-org 
      
    4. Press ‘y’ for any confirmation asked by the installer.

    Step 2 – Manage MongoDB Service

    MongoDB database server has been installed successfully on your system. Let’s execute the below command to start MongoDB servie.

    sudo systemctl start mongod.service 
    

    Also, run the below command to enable MongoDB to start on system boot.

    sudo systemctl enable mongod.service 
    

    Step 3 – Test MongoDB Version

    Finally, use the below command to check the installed MongoDB version on your system.

    mongod --version 
    
    db version v4.2.1
    git version: edf6d45851c0b9ee15548f0f847df141764a317e
    OpenSSL version: OpenSSL 1.1.0l  10 Sep 2019
    allocator: tcmalloc
    modules: none
    build environment:
        distmod: debian92
        distarch: x86_64
        target_arch: x86_64
    

    Also, connect MongoDB using the command line and execute some test commands for checking proper working.

    rahul@tecadmin:~$ mongo
    
    > use mydb;
    
    > db.test.save( { tecadmin: 100 } )
    
    > db.test.find()
    
      { "_id" : ObjectId("52b0dc8285f8a8071cbb5daf"), "tecadmin" : 100 }
    

    The post How to Install MongoDB 4.2 on Debian 10/9/8 appeared first on TecAdmin.

    ]]>
    https://tecadmin.net/install-mongodb-server-on-debian/feed/ 9
    How to Create Admin User In MongoDB https://tecadmin.net/create-drop-users-in-mongodb/ https://tecadmin.net/create-drop-users-in-mongodb/#comments Thu, 21 Apr 2016 09:37:11 +0000 https://tecadmin.net/?p=10201 In large-scale software engineering, we see problems in our implementation at every step. However, the biggest challenge remains to identify the root cause of the issues and fix them. In this article, we will learn how to implement user authentication with MongoDB and drop users in MongoDB when the user is no longer an employee [...]

    The post How to Create Admin User In MongoDB appeared first on TecAdmin.

    ]]>
    In large-scale software engineering, we see problems in our implementation at every step. However, the biggest challenge remains to identify the root cause of the issues and fix them. In this article, we will learn how to implement user authentication with MongoDB and drop users in MongoDB when the user is no longer an employee of your organization. MongoDB is one of the most popular NoSQL databases. It is a document database that stores data as documents rather than tables. If you are new to MongoDB or need a refresher, read our introductory article on using MongoDB:

    In this blog post, we’ll show you how to create an admin user and database user in MongoDB. Also, help you to drop users in MongoDB using the mongo shell.

    1. MongoDB – Create Admin User

    You can use the below commands to create users with admin privileges in your MongoDB server.

    mongo 
    
     use admin 
    
     db.createUser(
         {
           user:"myadmin",
           pwd:"secret",
           roles:[{role:"root",db:"admin"}]
         }
      )
    
     exit 
    

    Now try to connect with the above credentials through the command line.

    mongo -u myadmin -p  --authenticationDatabase admin 
    

    Once you have successfully created an admin account, you can secure the MongoDB instance by enabling the authentication.

    2. MongoDB – Create Database User

    First, we will create a user in our database, which will authenticate against our application. The following code snippet creates a user in the database. For example, we are creating a user account with read-write access to a database named “mydb”.

     use mydb 
    
     db.createUser(
        {
          user: "mydbuser",
          pwd: "mydbsecret",
          roles: ["readWrite"]
        }
     ) 
    
     exit 
    

    To verify authentication use the following command. Result 1 means authentication succeeded.

     db.auth('mydbuser','mydbsecret') 
    

    To list all users for a database, use the following command.

     db.getUsers() 
    

    3. Drop User in Mongodb

    Now that we have created a user and know how to grant them access to the collection, we need to know how to drop the user when they are no longer an employee of our organization. The following code snippet drops the user from the database.

     use mydb 
    
     db.dropUser('mydbuser') 
    

    This code drops the user “mydbuser” from the database.

    Conclusion

    MongoDB is a highly scalable database that is perfect for big data. It is used by companies such as Uber, Spotify, and eBay. In this article, we discussed how to create and drop users in MongoDB. If you have any questions or would like to provide feedback, feel free to leave a comment below.

    The post How to Create Admin User In MongoDB appeared first on TecAdmin.

    ]]>
    https://tecadmin.net/create-drop-users-in-mongodb/feed/ 2
    How to Install MongoDB 4.4 on Ubuntu 18.04 & 16.04 via PPA https://tecadmin.net/install-mongodb-on-ubuntu/ https://tecadmin.net/install-mongodb-on-ubuntu/#comments Fri, 01 Jan 2016 10:45:14 +0000 https://tecadmin.net/?p=4011 MongoDB is a full flexible index support and rich queries database. Mongodb is a NoSQL database. MongoDB provides large media storage with GridFS. Click here for more details about this version of MongoDB. This tutorial will help you to install MongoDB 4.4 community release on Ubuntu 20.04 LTS (Focal), 18.04 LTS (Bionic) and 16.04 LTS [...]

    The post How to Install MongoDB 4.4 on Ubuntu 18.04 & 16.04 via PPA appeared first on TecAdmin.

    ]]>
    MongoDB is a full flexible index support and rich queries database. Mongodb is a NoSQL database. MongoDB provides large media storage with GridFS. Click here for more details about this version of MongoDB.

    This tutorial will help you to install MongoDB 4.4 community release on Ubuntu 20.04 LTS (Focal), 18.04 LTS (Bionic) and 16.04 LTS (Xenial) systems.

    Step 1 – Setup Apt Repository

    First of all, import GPK key for the MongoDB apt repository on your system using the following command. This is required to test packages before installation

    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 656408E390CFB1F5
    

    Lets add MongoDB APT repository url in /etc/apt/sources.list.d/mongodb.list.

    Ubuntu 18.04 LTS:
    echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb.list
    
    Ubuntu 16.04 LTS:
    echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb.list
    

    Step 2 – Install MongoDB on Ubuntu

    After adding required APT repositories, use the following commands to install MongoDB on your systems. It will also install all dependent packages required for MongoDB.

    sudo apt update
    sudo apt install mongodb-org
    

    If you want to install any specific version of MongoDB, define the version number as below

    sudo apt install mongodb-org=4.4.1 mongodb-org-server=4.4.1 mongodb-org-shell=4.4.1 mongodb-org-mongos=4.4.1 mongodb-org-tools=4.4.1
    

    Step 3 – Manage MongoDB Service

    After installation, MongoDB will start automatically. To start or stop MongoDB uses init script. Below are the example commands to do.

    sudo systemctl enable mongod.service
    sudo systemctl start mongod.service
    

    Once the service started, check the status by running command:

    sudo systemctl status mongod.service
    

    Installing Mongodb on Ubuntu

    Use the following commands to stop or restart MongoDB service.

    sudo systemctl stop mongod.service
    sudo systemctl restart mongod.service
    

    Step 4 – Verify MongoDB Installation

    Finally, use the below command to check installed MongoDB version on your system.

    mongod --version 
    

    Output:

    db version v4.4.1
    Build Info: {
        "version": "4.4.1",
        "gitVersion": "ad91a93a5a31e175f5cbf8c69561e788bbc55ce1",
        "openSSLVersion": "OpenSSL 1.1.1  11 Sep 2018",
        "modules": [],
        "allocator": "tcmalloc",
        "environment": {
            "distmod": "ubuntu1804",
            "distarch": "x86_64",
            "target_arch": "x86_64"
        }
    }
    

    Also, connect MongoDB using the command line and execute some test commands for checking proper working.

    mongo 
    
    > use mydb;
    
    > db.colors.insert({ "id": 100, "color": "Pink"})
    > db.colors.insert({ "id": 101, "color": "Purple"})
    
    > db.colors.find()
    
      { "_id" : ObjectId("5f75a76194d0a08201f26f25"), "id" : 100, "color" : "Pink" }
      { "_id" : ObjectId("5f75a7d594d0a08201f26f26"), "id" : 101, "color" : "Purple" }
    
    

    More Useful tutorials

    Here is the list of useful tutorials for MongoDB server.

      Conclusion

      In this tutorial, you have learned to install MongoDB database server on Ubuntu system.

      The post How to Install MongoDB 4.4 on Ubuntu 18.04 & 16.04 via PPA appeared first on TecAdmin.

      ]]> https://tecadmin.net/install-mongodb-on-ubuntu/feed/ 29 How to Backup and Restore MongoDB Database https://tecadmin.net/backup-and-restore-mongodb-database/ https://tecadmin.net/backup-and-restore-mongodb-database/#comments Mon, 13 Oct 2014 09:50:34 +0000 https://tecadmin.net/?p=5165 MongoDB is a popular NoSQL database that is used for storing large amounts of data in a flexible and JSON-like format. As with any database, it is important to regularly back up your MongoDB data to ensure that you can recover from any unforeseen events such as data corruption, hardware failure, or accidental data deletion. [...]

      The post How to Backup and Restore MongoDB Database appeared first on TecAdmin.

      ]]>
      MongoDB is a popular NoSQL database that is used for storing large amounts of data in a flexible and JSON-like format. As with any database, it is important to regularly back up your MongoDB data to ensure that you can recover from any unforeseen events such as data corruption, hardware failure, or accidental data deletion. In this article, we will go over the steps for how to back up and restore a MongoDB database.

      Prerequisites

      Before you can start backing up and restoring your MongoDB database, you will need to have the following:

      • A MongoDB database installed and running on your system
      • The `mongodump` and `mongorestore` command line tools, which are included with the MongoDB installation
      • Access to the command line or terminal on your system

      Backing Up a MongoDB Database

      To back up a MongoDB database, you can use the `mongodump` command. This command creates a binary representation of the data in your database, which can be used to restore the database to a specific point in time.

      Here is the basic syntax for the `mongodump` command:

      mongodump [options]
      

      The mongodump command has a number of options that you can use to specify which database to back up, where to save the backup, and how to authenticate to the database. Some of the most commonly used options are:

      • --host: The hostname and port of the MongoDB server (e.g. localhost:27017)
      • --db: The name of the database to be backed up
      • --out: The directory where the backup will be saved
      • --username and --password: The credentials to use to authenticate to the database

      Here is an example of how you can use the `mongodump` command to back up a database called “mydb” on the localhost:

      mongodump --host localhost:27017 --db mydb --out /backup/dir 
      

      This will create a directory called `mydb` in the specified backup directory and save the binary representation of the data in the `mydb` database to it.

      You can also specify a specific collection using the `--collection` flag. For example, to create a backup of the “users” collection in the “mydb” database, you would run the following command:

      mongodump --collection users --db mydb --out /backup/dir 
      

      Even you can back up all of the available databases with the following command.

      mongodump --out /backup/dir  
      

      To authenticate the above requests use the `--username` and `--password` parameters.

      Restoring a MongoDB Database

      To restore a MongoDB database from a backup, you can use the `mongorestore` command. This command reads the binary data from a previous backup and imports it into a new or existing MongoDB database.

      Here is the basic syntax for the `mongorestore` command:

      mongorestore [options] 
      

      The “mongorestore” command has a number of options that you can use to specify which database to restore to, how to authenticate to the database and other options. Some of the most commonly used options are:

      • --host: The hostname and port of the MongoDB server (e.g. localhost:27017)
      • --db: The name of the database to restore to
      • --username and --password: The credentials to use to authenticate to the database
      • --drop: Drops all data from the target database before restoring the data

      Here is an example of how you can use the `mongorestore` command to restore a database from a backup stored in the directory `/backup/mongo/mydb`:

      mongorestore --db mydb /backup/mongo/mydb   
      

      Use --drop option delete all data from the target database before restoring it.

      mongorestore --db mydb --drop /backup/mongo/mydb  
      

      Conclusion

      In this article, we discussed how to back up and restore a MongoDB database. Backing up your database regularly is important to protect against data loss, and the `mongodump` and `mongorestore` utilities make it easy to create and restore backups of your MongoDB databases.

      The post How to Backup and Restore MongoDB Database appeared first on TecAdmin.

      ]]>
      https://tecadmin.net/backup-and-restore-mongodb-database/feed/ 1
      How To Setup MongoDB, PHP5 & Apache2 on Ubuntu https://tecadmin.net/setup-mongodb-php5-apache2-ubuntu/ https://tecadmin.net/setup-mongodb-php5-apache2-ubuntu/#comments Tue, 20 May 2014 10:42:45 +0000 https://tecadmin.net/?p=5262 MongoDB is an open source NoSQL database. These days mongodb is getting more popularity between web developers for their processing speed. And for PHP5 we all are aware that it is use widely use for faster development. In this article we are installing Latest MongoDB database with PHP5 and Apache2 web server on Ubuntu 14.04 [...]

      The post How To Setup MongoDB, PHP5 & Apache2 on Ubuntu appeared first on TecAdmin.

      ]]>
      MongoDB is an open source NoSQL database. These days mongodb is getting more popularity between web developers for their processing speed. And for PHP5 we all are aware that it is use widely use for faster development.

      mongo-php-apache

      In this article we are installing Latest MongoDB database with PHP5 and Apache2 web server on Ubuntu 14.04 LTS. This article will also work with other Ubuntu versions.

      Step 1: Install Apache2

      First install Apache2 web server on our system using following command, this is available under default repositories of Ubuntu.

      $ sudo apt-get install apache2
      

      After installing Apache2 it will by default start on port 80. You can change default apache2 port in /etc/apache2/ports.conf configuration file.

      Step 2: Install MongoDB

      First add the public key of repository in our system which is required for checking packages during installation and then add the 10gen apt repository in system with the following commands.

      $ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
      $ echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
      

      Now execute following command to install latest version of MongoDB. It default run on port 27017.

      $ sudo apt-get update
      $ sudo apt-get install mongodb-org mongodb-org-server
      

      Step 3: Install PHP5

      This is simple PHP5 installation on our system. You may also need to install other php modules as per your application requirements like php5-xml, php5-mbstring, php5-gettext etc.

      $ sudo apt-get install php5 php5-dev libapache2-mod-php5 apache2-threaded-dev php-pear php5-mongo
      

      Step 4: Install MongoDB PHP Module

      Finally we need to Install Mongo PECL extension and add in php configuration file. which provides connectivity between PHP and MongoDB.

      $ sudo pecl install mongo
      $ sudo echo "extension=mongo.so" >> /etc/php5/apache2/php.ini
      

      After installing the extension, lets restart apache service

      $ sudo service apache2 restart
      

      Step 5: Verify Setup

      At this stage we have complete all installation. But make sure that we have properly integrated MongoDB with PHP5. To test this create an phpinfo.php file using following value.

      <?php
       phpinfo();
      ?>
      

      Now put this file on servers document root (default is /var/www) and access through web browser.

        http://1.2.3.4/phpinfo.php
      

      mongodb-php

      The post How To Setup MongoDB, PHP5 & Apache2 on Ubuntu appeared first on TecAdmin.

      ]]>
      https://tecadmin.net/setup-mongodb-php5-apache2-ubuntu/feed/ 3
      How To Change MongoDB Default Data Path in Linux https://tecadmin.net/change-mongodb-default-data-path/ https://tecadmin.net/change-mongodb-default-data-path/#comments Sun, 18 May 2014 10:21:50 +0000 https://tecadmin.net/?p=5163 Most of the Sysadmins don’t prefer to use / directory to store their files or databases. So if they have installed MongoDB database server, by default it stored all data in /var/lib/mongo (version/os specific). In this tutorial, we will change the MongoDB default data path to other directories where we have attached a new disk [...]

      The post How To Change MongoDB Default Data Path in Linux appeared first on TecAdmin.

      ]]>
      Most of the Sysadmins don’t prefer to use / directory to store their files or databases. So if they have installed MongoDB database server, by default it stored all data in /var/lib/mongo (version/os specific). In this tutorial, we will change the MongoDB default data path to other directories where we have attached a new disk (EBS volume in AWS).

      mongodb-medium-logo

      Instruction’s to Change MongoDB Default Data Path:

      1. Before making any changes, stop mongodb service

      sudo systemctl stop mongod.service
      

      2. Now change the location mongo directory to elsewhere on the filesystem as per need. For this tutorial, create a data directory under /home and sync directory /var/lib/mongo there using rsync.

      After that create a symbolic link to a new directory to the original mongo directory location.

      #### Copy mongo directory to new directory: 
      sudo mkdir /home/data/
      sudo rsync -av /var/lib/mongo /home/data/
      
      #### Rename old directory for backup: 
      sudo mv /var/lib/mongo /var/lib/mongo.bak
      
      #### Create symbolic link to the new location:
      sudo ln -s /home/data/mongo /var/lib/mongo
      

      Update: These steps are suggested by our reader in comments and I have also tested on CentOS 8 system. Thank You Mohamed-yassine BELATAR,

      3. Finally, start the MongoDB service using the following command. Now MongoDB will start using new directory (/home/data/mongo) as default data directory.

      sudo systemctl start mongod.service
      

      All done.

      The post How To Change MongoDB Default Data Path in Linux appeared first on TecAdmin.

      ]]>
      https://tecadmin.net/change-mongodb-default-data-path/feed/ 4