Monday, August 18, 2014

Getting Started

Document

  • an ordered set of keys with associated values: {"greeting" : "Hello, world!", "foo" : 3}
  • Key/value pairs in documents are ordered
  • MongoDB is type-sensitive and case-sensitive

Collection

  • A collection is a group of documents
  • Subcollections: One convention for organizing collections is to use namespaced subcollections separated by the . character. Eg: blog.posts and blog.authors
  • There is no relationship between blog and posts/authors; indeed blog doesn't have to exist
Database
  • MongoDB groups collections into databases.
Fully qualified name = <name of database>.<name of collection>.<name of subcollection>

Starting MongoDB

./mongod

default directory: /data/db
Port: 27017
HTTP Port: Port + 1000 = 28017

MongoDB Shell

./mongo

Shell attempts to connect to a MongoDB server on startup
Shell is a full-featured JavaScript interpreter

On startup, the shell conects to the test database on a MongoDB server and assigns this database connection to the global variable db

> use blog
switched to db blog

>db
blog

Basic operations with the Shell

Create, Read, Update and Delete (CRUD)

Adding a document to a collection
> post = { "title" : "My Blog Post",
                 "content" : "Here's my blog post",
                 "date : new Date()
              };
> db.blog.insert(post)

Read
> db.blog.findOne()

Update
> post.comments = []
> db.blog.update({title : "My Blog Post"}, post)
> db.blog.find()
{
     "_id" : ObjectId("4b23c3ca7525f35f94b60a2d"),
     "title" : "My Blog Post",
     "content" : "Here's my blog post.",
     "date" : "Sat Dec 12 2009 11:23:21 GMT-0500 (EST)"
     "comments" : [ ]
}

Delete
>db.blog.remove({title : "My Blog Post"})

Inconvenient collection names


If we are trying to access the version collection, we cannot say db.version because db.version is a database
function.(is a property of the database class)
> db.version
   function () {
        return this.serverBuildInfo().version;
   }

> db.getCollection("version")
> db.getCollection("foo-bar")

x.y is identical to x['y'].

var collections = ["posts", "comments", "authors"];
for (i in collections) 
{
         doStuff(db.blog[collections[i]]);
}

Instead of this:
doStuff(db.blog.posts);
doStuff(db.blog.comments);
doStuff(db.blog.authors);

Data Types

null
   {"x" : null}

boolean
   {"x" : true}

32-bit integer

64-bit integer

64-bit floating point number
   {"x" : 3.14}

string
   {"x" : "foobar"}

symbol

object id
  {"x" : ObjectId()}

date
  {"x" :  new Date()}

regular expression
  {"x" : /foobar/i}

code
  {"x" : function() { ... }}

binary data

maximum value

minimum value

undefined
   {"x" : undefined}

array
   {"x" : ["a", "b", "c"]}

embedded document
   {"x" : {"foo" : "bar"}}

_id and ObjectIds 
ObjectIds (12 bytes)
0 1 2 3         4 5 6     7 8 9      10 11
Timestamp Machine   PID     Increment

No comments:

Post a Comment