Saturday, January 5, 2019

MongoDB basic commands

1. Setup MongoDB

  • Download: https://www.mongodb.com/download-center/community

  • Extract folder
    tar -zxvf mongodb-osx-x86_64-xx.tgz -C /path/to/container/folder

  • Add to $PATH
    Find out which current shell you are working on.
    zsh open ~/.zshrc
    bash open ~/.bashrc
    add lines at the end of the file.
    export MONGODB_HOME=~/Workspace/mongodb-osx-x86_64-xx/
    export PATH=$MONGODB_HOME/bin:$PATH

    Reload the environment variables for current shell
    # e.g
    source ~/.zshrc

  • Create the directory where MongoDB stores data
    sudo mkdir /data/db
    sudo chown -R `id -un` /data/db

  • Start MongoDB
    mongod

    For now , you have a mongodb server is running on default port 2017 without authentication, the data is stored on /data/db
2. Basic client commands

# connect to server
mongo

# list databases;
show databases;

# use a database
use ${db_name}

# list collections;
show collections;

# form now we can perform collection methods
db.${collectionName}.${command}

find({})
findOne()
find({"_id": new IdObject("${docId}")})
find({ <field>: { $regex: /pattern/, $options: '<options>' }})
deleteMany({})
deleteOne({})
remove({})
drop()

Checkout collection methods

2.Delete database

# from commandline
mongo ${dbName} --eval "db.dropDatabase()"

# inside mongoClient
use ${dbName}
db.dropDatabase()



No comments:

Post a Comment