Mongo Basics

  1. Connect to a database from a system prompt, start mongo

     
    mongo 
    By default, mongo looks for a database server listening on port 27017 on the localhost interface. To connect to a server on a different port or interface, use the --port and --host options.
     
    mongo --port 27017 -u siteUserAdmin -p password --authenticationDatabase admin

  2. Display the list of databases, with the following operations.

     
    show dbs

  3. Switch to a new database named mydb, with the following operation:

     
    use mydb

  4. Use auth to authenticate a connection

     
    db.auth( "username", "password" )

  5. Check yoor corrent session

     
    db

  6. Display help

     
    help

  7. Create documents named j and k:

     
    j = { name : "mongo" }
    k = { x : 3 }

  8. Insert the j and k documents into the testData collection

     
    db.testData.insert( j )
    db.testData.insert( k )
    When you insert the first document, the mongod will create both the mydb database and the testData collection.

  9. Confirm that the testData collection exists

     
    show collections

  10. Confirm that the documents exist in the testData collection

     
    db.testData.find()
    Result will be
     
    { "_id" : ObjectId("4c2209f9f3924d31102bd84a"), "name" : "mongo" }
    { "_id" : ObjectId("4c2209fef3924d31102bd84b"), "x" : 3 }

  11. Working with the Cursor When you query a collection, MongoDB returns a cursor. object that contains the results of the query. The mongo shell then iterates over the cursor to display the results. Rather than returning all results at once, the shell iterates over the cursor 20 times to display the first 20 results and then waits for a request to iterate over the remaining results. In the shell, enter it to iterate over the next set of results.

  12. Iterate over the Cursor with a Loop

     
    var c = db.testData.find()
    while ( c.hasNext() ) printjson( c.next() )
    To find the document at the array index 4, use the following operation:
     
    printjson( c [ 0 ] )