Connect to a database from a system prompt, start mongo
mongo
mongo --port 27017 -u siteUserAdmin -p password --authenticationDatabase admin
Display the list of databases, with the following operations.
show dbs
Switch to a new database named mydb, with the following operation:
use mydb
Use auth to authenticate a connection
db.auth( "username", "password" )
Check yoor corrent session
db
Display help
help
Create documents named j and k:
j = { name : "mongo" }
k = { x : 3 }
Insert the j and k documents into the testData collection
db.testData.insert( j )
db.testData.insert( k )
Confirm that the testData collection exists
show collections
Confirm that the documents exist in the testData collection
db.testData.find()
{ "_id" : ObjectId("4c2209f9f3924d31102bd84a"), "name" : "mongo" }
{ "_id" : ObjectId("4c2209fef3924d31102bd84b"), "x" : 3 }
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.
Iterate over the Cursor with a Loop
var c = db.testData.find()
while ( c.hasNext() ) printjson( c.next() )
printjson( c [ 0 ] )