Monday, 3 June 2019

MongoDB essentials: Setup and basic operations

MongoDB is a popular NoSQL database management system that is often used in the servers of modern applications. This blogpost shows the essentials of working with MongoDB.
  1. Setup MongoDB in Ubuntu
    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
    echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
    sudo apt-get update
    sudo apt-get install -y mongodb-org
  2. Start/Stop MongoDB server
    //Start
    sudo service mongod start
    //Check status and get the PID
    service mongod status
    //Check if mongodb is running
    ps -aux | grep 16822
    //Check if mongodb server is listening at default port 27017
    netstat -tulnp | grep 2701
    //Stop
    sudo service mongod stop
    //Restart
    sudo service mongod restart
  3. Essential operations
    //Start Mongo Shell
    mongo
    //List all databases
    show dbs
    // Switch current database to DB_NAME. The mongo shell variable db is set to the current database.
    use DB_NAME
    //Print a list of users for current database
    show users
    //Print a list of all roles, both user-defined and built-in, for the current database
    show roles
    //Create database
    use mynewdb
    db.users.insert({ id: 1 })
    //Drop database
    db.dropDatabase()
    //Create a new collection in the current database
    db.createCollection("NewCollectionName")
    //Print a list of all collections for current database
    show collections
    //Add new document to a collection
    db.COLLECTION_NAME.insert(document)
    //Query document
    db.COLLECTION_NAME.find(condition)
    example: db.users.find({"id": 1001})
    //Show all documents
    db.COLLECTION_NAME.find();
    //Update document
    db.users.update(CONDITION, UPDATED DATA, OPTIONS)
    //Delete document
    db.COLLECTION_NAME.remove(CONDITION)
    //More SQL liked MongoDB commands
    LINK

2 comments:

  1. JavaScript is a scripting language you can use to make web pages interactive. It is one of the core technologies of the web, along with HTML and CSS, and is supported by all modern browsers. javascript courses for beginners

    ReplyDelete
  2. Very informative blog. I especially like content that has to do with beauty and fitness, so it’s refreshing to me to see what you have here. Keep it up! facial exercises Tutoriales de java en espanol

    ReplyDelete