Tag: MongoDB

  • How to export MongoDB collection to CSV

    How to export MongoDB collection to CSV

    mongoexport command is used to export MongoDB collection into CSV or JSON format.

    Syntax

    mongoexport --db DB_NAME --collection COLLECTION_NAME --fields FIELDS_HERE --type=csv --out NAME_OF_OUT_FILE
    

    Where

    DB_NAME = name of the database
    COLLECTION_NAME = name of the collection
    FIELDS_HERE = comma separated list of fields.
    NAME_OF_OUT_FILE = name of the CSV file
    

    By default MongoDB connect to localhost port 27017

    Example

    Export mongodb collection to CSV file

    mongoexport --db main --collection users --fields  name,email,level --type csv --out users.csv
    

    In this case, we export fields “name,email,level” from “users” collection in database “main”. Result will be saved to file users.csv in current directory.

    Back to MongoDB

  • Migrate database from MongoDB Atlas to your server

    Migrate database from MongoDB Atlas to your server

    MongoDB Atlas is a hosted MongoDB server hosting in cloud. If you are starting with MongoDB, they have free hosting, that work for smaller sites.

    https://www.mongodb.com/cloud

    MongoDB Atlas

    On this page, you can see the version of MongoDB is Version 4.2.10. You need to install same or newer version of MongoDB on your server.

    MongoDB documentation have detailed instructions for installing MongoDB on various Operating systems.

    https://docs.mongodb.com/manual/administration/install-on-linux/

    Take MongoDB backup

    MongoDB atlas provide you command to take backup. On “Clusters” page, click the 3 dots, then select command line tools. Next page will show you command to take backup of your MongoDB database.

    mkdir /root/mongodb_backup
    cd /root/mongodb_backup
    mongodump --uri mongodb+srv://YOURNAME_HERE:[email protected]/DATABASE_NAME_HERE
    

    You can find database name in atlas, for this, click “Cluster0”, then go to Collections tab. You will see database name on this page.

    Once you run the mongodump command, it will create a folder “dump” and save backup inside.

    backup mongodb database using mongodump

    Restart MongoDB backup

    To restart MongoDB backup locally, run

    mongorestore --username=USER_NAME_HERE --password=PW_HERE --authenticationDatabase "admin"  /root/mongodb_backup/dump/
    

    USER_NAME_HERE and PW_HERE is MongoDB user and password. You can enable MongoDB authentication following instructions at

    https://docs.mongodb.com/guides/server/auth/

    Update Application to use local MongoDB

    The application used following connection string

    mongoose.connect("mongodb+srv://USER:[email protected]/DB_NAME?retryWrites=true&w=majority", {
    

    I replaced it with

    mongoose.connect("mongodb://USER:[email protected]:27017/DB_NAME?retryWrites=true&w=majority&authSource=admin", {
    
  • Start MongoDB from command line

    To start MongoDB from command line, run

    mongod --auth --dbpath /path/to/mongodb
    

    See MongoDB

  • Install MongoDB 4.0 on CentOS 7

    To install MongoDB 4.0 (for other versions, see release note) on CentOS 7, create file

    vi /etc/yum.repos.d/mongodb-org-4.0.repo
    

    Add content

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

    Install MongoDB with

    yum install -y mongodb-org
    

    Enable MongoDB start on boot

    systemctl enable mongod
    

    Start Mongo DB with

    systemctl start mongod
    

    To see mongoDB version, run

    [root@ns3084948 ~]# mongo --version
    MongoDB shell version v4.0.10
    git version: c389e7f69f637f7a1ac3cc9fae843b635f20b766
    OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
    allocator: tcmalloc
    modules: none
    build environment:
        distmod: rhel70
        distarch: x86_64
        target_arch: x86_64
    [root@ns3084948 ~]#
    

    To see if mongoDB running

    [root@ns3084948 ~]# netstat -lntp | grep mongo
    tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      10349/mongod        
    [root@ns3084948 ~]# 
    

    Or use

    [root@ns3084948 ~]# systemctl status mongod
    ● mongod.service - MongoDB Database Server
       Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
       Active: active (running) since Tue 2019-06-04 06:08:01 BST; 18min ago
         Docs: https://docs.mongodb.org/manual
      Process: 10347 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=0/SUCCESS)
      Process: 10344 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited, status=0/SUCCESS)
      Process: 10341 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (code=exited, status=0/SUCCESS)
      Process: 10338 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, status=0/SUCCESS)
     Main PID: 10349 (mongod)
       Memory: 46.7M
       CGroup: /system.slice/mongod.service
               └─10349 /usr/bin/mongod -f /etc/mongod.conf
    
    Jun 04 06:07:57 ns3084948.ip-145-239-4.eu systemd[1]: Starting MongoDB Database Server...
    Jun 04 06:07:58 ns3084948.ip-145-239-4.eu mongod[10347]: 2019-06-04T06:07:58.013+0100 I CONTROL  [main] WARNING: Cannot detect if NUMA interleaving is enabled. Failed to probe "/sys/devices...ssion denied
    Jun 04 06:07:58 ns3084948.ip-145-239-4.eu mongod[10347]: about to fork child process, waiting until server is ready for connections.
    Jun 04 06:07:58 ns3084948.ip-145-239-4.eu mongod[10347]: forked process: 10349
    Jun 04 06:08:01 ns3084948.ip-145-239-4.eu mongod[10347]: child process started successfully, parent exiting
    Jun 04 06:08:01 ns3084948.ip-145-239-4.eu systemd[1]: Started MongoDB Database Server.
    Hint: Some lines were ellipsized, use -l to show in full.
    [root@ns3084948 ~]# 
    
  • Find MongoDB version

    Find MongoDB version

    To find MongoDB version, login to MongoDB server using command

    mongo
    

    Now run

    db.version()
    

  • MongoDB delete Database

    To delete a database in MongoDB, run

    mongo
    use DBNAME
    db.dropDatabase()
    
  • Install MongoDB 4 on Debian 9

    You can see detailed instruction on how to install on MongoDB web site.

    First add key

    apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
    

    For Debian 8, run

    echo "deb http://repo.mongodb.org/apt/debian jessie/mongodb-org/4.0 main" > /etc/apt/sources.list.d/mongodb-org-4.0.list
    

    For Debian 9, run

    echo "deb http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 main" > /etc/apt/sources.list.d/mongodb-org-4.0.list
    

    Now install mongoDB with

    apt-get update
    apt-get install -y mongodb-org
    

    Once installed, you can check version with

    root@ip-172-31-25-155:~# mongod --version
    db version v4.0.4
    git version: f288a3bdf201007f3693c58e140056adf8b04839
    OpenSSL version: OpenSSL 1.1.0f  25 May 2017
    allocator: tcmalloc
    modules: none
    build environment:
        distmod: debian92
        distarch: x86_64
        target_arch: x86_64
    root@ip-172-31-25-155:~# 
    

    Enable MongoDB start on boot

    systemctl enable mongod
    

    To start/stop mongodb

    systemctl start mongod
    systemctl stop mongod
    
  • Getting Started with MongoDB

    After MongoDB is installed, you can start MongoDB client with command.

    mongo
    

    List All Databases

    To see list of all available database, use

    show dbs
    

    Create A Database

    To create a database, run

    use DB_NAME
    

    This will create a new database if not present and switch to it.

    See all Collections

    Once you switched to a database using “use DB_NAME” command, you can see collections (or tables) in a database with command

    show collections
    

    Creating Tables

    In MongoDB, tables are called Collections. To create a collection, use

    db.createCollection("COLLECTION_NAME")
    

    Here i create a collection with name “servers”.

    Inserting Data into a Collection

    You can insert data into a collection in Jason format. To insert use following format

    db.COLLECTION_NAME.insert(JSON_DATA)
    

    Example

    db.servers.insert({hostname: "server22.hosthat.com", ip: "144.217.71.213", os: "CloudLinux 7.4", ram: "64G", cpu: "Intel(R) Xeon(R) CPU D-1521 @ 2.40GHz"})
    

    When you insert data MongoDB will auto create a unique “_id” field.

    Listing Data in Collection

    To list all available data in a collection, use

    db.COLLECTION_NAME.find()
    

    This will list all data. To list specific data, you can pass JSON string to find(), for example, to find all servers to 64G RAM, use

    db.servers.find({ram: "64G"})
    

    MongoDB

  • Install MongoDB in Ubuntu

    To install MongoDB in Ubuntu/Debian, run

    apt install mongodb
    

    Configuration file for MongoDB is

    /etc/mongodb.conf
    

    To see status of MongoDB, run

    systemctl status mongodb
    

    To start/stop

    systemctl start mongodb
    systemctl stop mongodb
    

    Create a User

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

    Now you need to enable authentication, this can be done by editing /etc/mongodb.conf

    vi /etc/mongodb.conf
    

    Uncomment the line

    auth = true
    

    Restart MongoDB

    systemctl restart mongodb
    

    Now you can login with

    mongo -u  "root" -p "serverok123" --authenticationDatabase "admin"
    

    To verify all works, run some command, for example

    show dbs
    

    On Ubuntu 18.04, default MongoDB version is

    ubuntu@ip-172-31-8-76:~$ mongo -u  "root" -p "serverok123" --authenticationDatabase "admin"
    MongoDB shell version v3.6.3
    connecting to: mongodb://127.0.0.1:27017
    MongoDB server version: 3.6.3
    Welcome to the MongoDB shell.
    For interactive help, type "help".
    For more comprehensive documentation, see
    	http://docs.mongodb.org/
    Questions? Try the support group
    	http://groups.google.com/group/mongodb-user
    Server has startup warnings: 
    2018-12-22T17:06:15.171+0000 I STORAGE  [initandlisten] 
    2018-12-22T17:06:15.171+0000 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
    2018-12-22T17:06:15.171+0000 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
    > db.version()
    3.6.3
    > 
    

    MongoDB

  • Install MongoDB on CentOS 7

    To find latest MongoDB version, see

    https://docs.mongodb.com/manual/release-notes/

    To install MongoDB 3.6 on CentOS 7, create file

    vi /etc/yum.repos.d/mongodb-org-3.6.repo
    

    Add

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

    Refer https://docs.mongodb.com/master/tutorial/install-mongodb-on-red-hat/

    Now install MongoDB with

    yum install mongodb-org
    

    Enable MongoDB start on boot with

    systemctl enable MongoDB
    

    To start MongoDB, run

    systemctl start mongod
    

    You can check status of MongoDB with

    systemctl status mongod
    

    MongoDB