MongoDB Basics

From Training Material
Jump to navigation Jump to search


<slideshow style="nobleprog" headingmark="⌘" incmark="…" scaled="false" font="Trebuchet MS" >

title
MongoDB - Basics
author


Kamil Baran kb@NobleProg.pl

</slideshow>

Table of contents⌘

Introduction ⌘

  • MongoDB is a document-oriented database
  • replaces the concept of a "row" with a more flexible model, the "document"
  • no predefined schemas

CRUD ⌘

Create

use NobleProg
person = {"Name":"Sean Connery", "Nationality":"Great Britain"}
db.people.insert(person)

Read

db.people.find()
db.people.findOne()
db.people.find().pretty()

Update

person.Occupation = "Actor"
db.people.update({"Name":"Sean Connery"}, person)
db.people.findOne()

Delete

db.people.remove({"Name":"Sean Connery"})
db.people.remove({})
db.people.findOne()

MongoDB Shell ⌘

$ mongo
MongoDB shell version: 2.6.4
connecting to: test
>

$ mongo HostName:PortNumber/DatabaseName
$ mongo localhost:27017/test

$ mongo --nodb
> conn = new Mongo("localhost:27017")
connection to localhost27017
> db = conn.getDB("NobleProg")
NobleProg

Using help ⌘

  • mongo is a JavaScript shell, help is available in JavaScript on-line documentation
  • use built-in help for MongoDB-specific functionality
  • type function name without parentheses to see what the function is doing
> help
    db.help()            help on db methods
    db.mycoll.help()     help on collections methods
    ...
    exit                 quit mongo shell
>
> db.NobleProg.stats
function ( scale ){
    return this._db.runCommand( { collstats : this._shortName , scale : scale } );
}
>
> db.NobleProg.stats()
{ "ok" : 0, "errmsg" : "Collection [test.NobleProg] not found." }
>

Running Scripts ⌘

  • mongo can execute JavaScript files
  • scripts have access to all global variables (e.g. "db")
  • shell helpers (e.g. "show collections") do not work from files
    • use valid JavaScript equivalents (e.g. "db.getCollectionNames()")
  • use load() to run script directly from Mongo Shell
  • use .mongorc.js for frequently-loaded scripts
  • startup options: --norc, --quiet
$ mongo script.js
MongoDB shell version: 2.6.4
connecting to: test
script.js was executed successfully!
$ mongo --quiet script.js
script.js was executed successfully!
$ mongo
MongoDB shell version: 2.6.4
connecting to: test
> load(script.js)
script.js was executed successfully!