Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Monday, April 24, 2023

Using MongoDB


In this post we review the basic steps of start using an existing MongoDB. See this post for installing a MongoDB on a kubernetes cluster. 


To add a new document in a a new collection in a new database, we need to perform the following actions (see examples for commands below):

  1. Use the new db
  2. Create new user in the new db
  3. Grant permissions to the new user in the new db
  4. Switch to the new user
  5. Add thew new document


Databases Commands

  • use db1
    Set a database for the next operations
    The database is automatically created when we store data in it

  • show dbs
    Show list of databases

Users Commands

  • db.runCommand({connectionStatus : 1})
    Display current user information

  • db.createUser({ user: 'alon', pwd: 'alon', roles: [] })
    Create a new user

  • db.grantRolesToUser('alon', [{ role: 'readWrite', db: 'db1' }])
    Add permissions to user

  • db.auth('alon','alon')
    Switch to a user in the current database

Documents Commands

  • db.collection1.insertOne({name:'John', Age:45})
    Insert new document

  • db.collection1.find()
    Get all documents from the collection

  • db.collection1.find({'Age':45})
    Query for specific documents

  • db.collection1.insertMany([{'Name':"Foo"},{"Name":"Bar"}])
    Insert multiple documents

    Indexes Command

    • db.collection1.createIndex({'name':1})
      Create new index



    No comments:

    Post a Comment