Wednesday, August 20, 2014

Querying

Introduction to find

find method is used to perform queries in MongoDB
Querying returns a subset of documents in a collection.

db.c.find() is same as db.c.find({})
   which matches every document in the collection
Eg:
db.users.find({"age" : 27})
db.users.find({"username" : "joe"})

and operator
db.users.find({"username" : "joe", "age" : 27})   , acts as an "and" operator

Specifying which Keys to and not to return

> db.users.find({}, {"username" : 1, "email" : 1})
{
     "_id" : ObjectId("4ba0f0dfd22aa494fd523620"),
     "username" : "joe",
     "email" : "joe@example.com"
}  

Avoid printing _id
> db.users.find({}, {"fatal_weakness" : 0})

> db.users.find({}, {"username" : 1, "_id" : 0})
{
     "username" : "joe",
}

Limitations

The value of a query document must be a constant as far as the database is concerned.
That is, it cannot refer to the value of another key in the document.

Query Criteria

"$lt", "$lte", "$gt", and "$gte" are all comparison operators

Eg:
> db.users.find({"age" : {"$gte" : 18, "$lte" : 30}})

> start = new Date("01/01/2007")
> db.users.find({"registered" : {"$lt" : start}})

> db.users.find({"username" : {"$ne" : "joe"}})

OR Queries

> db.raffle.find({"ticket_no" : {"$in" : [725, 542, 390]}})

Allows you to specify criteria of different types
> db.users.find({"user_id" : {"$in" : [12345, "joe"]})

> db.raffle.find({"ticket_no" : {"$nin" : [725, 542, 390]}})

to find documents where "ticket_no" is 725 or "winner" is true
> db.raffle.find({"$or" : [{"ticket_no" : 725}, {"winner" : true}]})

"$or" can contain other conditionals
> db.raffle.find({"$or" : [{"ticket_no" : {"$in" : [725, 542, 390]}},
{"winner" : true}]})

$not

It can be applied on top of any other criteria

"$mod" queries for keys whose values, when divided by the first value given, have a remainder of the second value

> db.users.find({"id_num" : {"$mod" : [5, 1]}})

> db.users.find({"id_num" : {"$not" : {"$mod" : [5, 1]}}})

Type-Specific Queries

> db.c.find({"y" : null})
{ "_id" : ObjectId("4ba0f0dfd22aa494fd523621"), "y" : null }

null not only matches itself but also matches “does not exist

> db.c.find({"z" : null})
{ "_id" : ObjectId("4ba0f0dfd22aa494fd523621"), "y" : null }
{ "_id" : ObjectId("4ba0f0dfd22aa494fd523622"), "y" : 1 }
{ "_id" : ObjectId("4ba0f148d22aa494fd523623"), "y" : 2 }




Monday, August 18, 2014

Creating, Updating, and Deleting Documents

Creating, Updating, and Deleting Documents

Inserting and saving documents

Use the collection's insert method

> db.foo.insert({"bar" : "baz"})

Removing Documents

> db.users.remove()

Also takes a query document as a parameter

> db.users.remove({"user" : "jones"})

> db.users.drop()

Updating Documents

The last update wins.

Document Replacement

To convert the following
{
    "_id" : ObjectId("4b2b9f67a1f631733d917a7a"),
    "name" : "joe",
    "friends" : 32,
    "enemies" : 2
}

to
{
    "_id" : ObjectId("4b2b9f67a1f631733d917a7a"),
    "username" : "joe",
    "relationships" :
    {
        "friends" : 32,
        "enemies" : 2
    }
}

> var joe = db.users.findOne({"name" : "joe"});
> joe.relationships = {"friends" : joe.friends, "enemies" : joe.enemies};
{
    "friends" : 32,
    "enemies" : 2
}
> joe.username = joe.name;
"joe"
> delete joe.friends;
true
> delete joe.enemies;
true
> delete joe.name;
true
> db.users.update({"name" : "joe"}, joe);

Using Modifiers

Partial updates can be done extremely efficiently by using atomic update modifiers.
Update modifiers can specify complex update operations such as
  • altering
  • adding
  • removing keys
  • manipulating arrays and embedded documents

$set
"$set" sets the value of a key. If the key does not yet exist, it will be created

Creating a new key in a document
> db.users.findOne()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"name" : "joe",
"age" : 30,
"sex" : "male",
"location" : "Wisconsin"
}
> db.users.update({"_id" : ObjectId("4b253b067525f35f94b60a31")},
... {"$set" : {"favorite book" : "war and peace"}})
> db.users.findOne()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"name" : "joe",
"age" : 30,
"sex" : "male",
"location" : "Wisconsin",
"favorite book" : "war and peace"
}

Updating the value of an existing key in a document
> db.users.update({"name" : "joe"},
... {"$set" : {"favorite book" : "green eggs and ham"}})

Updating the value of an existing key to an array in a document
db.users.update({"name" : "joe"},
... {"$set" : {"favorite book" :
... ["cat's cradle", "foundation trilogy", "ender's game"]}})

To remove a key
db.users.update({"name" : "joe"},
... {"$unset" : {"favorite book" : 1}})

Changing an embedded document
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"title" : "A Blog Post",
"content" : "...",
"author" : {
"name" : "joe",
"email" : "joe@example.com"
}
}
> db.blog.posts.update({"author.name" : "joe"}, {"$set" : {"author.name" : "joe schmoe"}})
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"title" : "A Blog Post",
"content" : "...",
"author" : {
"name" : "joe schmoe",
"email" : "joe@example.com"
}
}

$inc
The "$inc" modifier can be used to
  • change the value for an existing key or 
  • to create a new key if it does not already exist

Creating a new key in a document
> db.games.insert({"game" : "pinball", "user" : "joe"})
> db.games.update({"game" : "pinball", "user" : "joe"},
... {"$inc" : {"score" : 50}})
> db.games.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"game" : "pinball",
"name" : "joe",
"score" : 50
}

Increasing value of an existing key
> db.games.update({"game" : "pinball", "user" : "joe"},
... {"$inc" : {"score" : 10000}})
> db.games.find()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"game" : "pinball",
"name" : "joe",
"score" : 10050
}

$push

adds an element to the end of an array if the key exists
creates a new array if it does not

> db.blog.posts.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"title" : "A blog post",
"content" : "..."
}
> db.blog.posts.update({"title" : "A blog post"},
  {$push : {"comments" : {"name" : "joe", "email" : "joe@example.com", "content" : "nice post."}}})
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"title" : "A blog post",
"content" : "...",
"comments" : [
{
"name" : "joe",
"email" : "joe@example.com",
"content" : "nice post."
}
]
}

To add another comment, use $push again

> db.blog.posts.update({"title" : "A blog post"},
   {$push : {"comments" : {"name" : "bob", "email" : "bob@example.com", "content" : "good post."}}})
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"title" : "A blog post",
"content" : "...",
"comments" : [
{
"name" : "joe",
"email" : "joe@example.com",
"content" : "nice post."
},
{
"name" : "bob",
"email" : "bob@example.com",
"content" : "good post."
}
]
}

Adding a value to an array only if it is not present
> db.papers.update({"authors cited" : {"$ne" : "Richie"}},
... {$push : {"authors cited" : "Richie"}})

$addToSet

Use $addToSet to prevent duplicates

> db.users.findOne({"_id" : ObjectId("4b2d75476cc613d5ee930164")})
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"username" : "joe",
"emails" : [
"joe@example.com",
"joe@gmail.com",
"joe@yahoo.com"
]
}
> db.users.update({"_id" : ObjectId("4b2d75476cc613d5ee930164")},
... {"$addToSet" : {"emails" : "joe@gmail.com"}})
> db.users.findOne({"_id" : ObjectId("4b2d75476cc613d5ee930164")})
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"username" : "joe",
"emails" : [
"joe@example.com",
"joe@gmail.com",
"joe@yahoo.com",
]
}

$addToSet with $each
to add multiple unique values
> db.users.update({"_id" : ObjectId("4b2d75476cc613d5ee930164")},
{"$addToSet" : {"emails" : {"$each" : ["joe@php.net", "joe@example.com", "joe@python.org"]}}})

$pop
{$pop : {key : 1}} removes an element from the end of the array.
{$pop : {key : -1}} removes it from the beginning

$pull
"$pull" is used to remove elements of an array that match the given criteria.
> db.lists.insert({"todo" : ["dishes", "laundry", "dry cleaning"]})
> db.lists.update({}, {"$pull" : {"todo" : "laundry"}})
> db.lists.find()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"todo" : [
"dishes",
"dry cleaning"
]
}

Positional array modifications
> db.blog.posts.findOne()
{
"_id" : ObjectId("4b329a216cc613d5ee930192"),
"content" : "...",
"comments" : [
        {
                "comment" : "good post",
                "author" : "John",
                "votes" : 0
        },
        {
                "comment" : "i thought it was too short",
                "author" : "Claire",
                "votes" : 3
        },
        {
                "comment" : "free watches",
                "author" : "Alice",
                "votes" : -1
        }
    ]
}

> db.blog.update({"post" : post_id},
... {"$inc" : {"comments.0.votes" : 1}})

We don’t know what index of the array to modify without querying for the document first and examining it.
MongoDB has a positional operator, "$", that figures out which element of the array the query document
matched and updates that element.

db.blog.update({"comments.author" : "John"},
... {"$set" : {"comments.$.author" : "Jim"}})

Upserts

An upsert is a special type of update

If no document is found that matches the update criteria, a new document will be created by combining the criteria and update documents.

If a matching document is found, it will be updated normally.

Benefits:
  • We avoid making a round-trip to the database
  • We also avoid a race condition where more than a document can be inserted for a given URL.
> db.math.remove()
> db.math.update({"count" : 25}, {"$inc" : {"count" : 3}}, true)
> db.math.findOne()
{
     "_id" : ObjectId("4b3295f26cc613d5ee93018f"),
     "count" : 28
}

The upsert creates a new document with a "count" of 25 and then increments that by 3, giving us a document
where "count" is 28.

Updating Multiple Documents

Updates, by default, update only the first document found that matches the criteria
To modify all of the documents matching the criteria, you can pass true as the fourth parameter to update

> db.users.update({birthday : "10/13/1978"},
... {$set : {gift : "Happy Birthday!"}}, false, true)

getLastError

To see the number of documents updated by a multiple update
The "n" key will contain the number of documents affected by the update

> db.runCommand({getLastError : 1})
{
     "err" : null,
     "updatedExisting" : true,
     "n" : 5,
     "ok" : true
}

Update generic interface

<collection instance>.update(<query document>,   , <is an upsert? i.e. should insert and update>, <should update multiple documents>)

Returning Updated Documents







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

Basics

MongoDB

MongoDB is a document-oriented database.

Easy Scaling:
Scaling a database comes down to the choice between scaling up (getting a bigger machine) or scaling out (partitioning data across more machines)

MongoDB was designed from the beginning to scale out. Its document-oriented data
model allows it to automatically split up data across multiple servers.

Essential Features

Indexing
Stored JavaScript
   Developers can store and use JavaScript functions and values on the server side.
Aggregation
   Supports MapReduce and other aggregation tools.
Fixed-size collections
File storage

MongoDB uses a binary wire protocol as the primary mode of interaction with the server (as opposed to the protocol with more overhead, like HTTP/REST)

Adds dynamic padding to documents and preallocates data files.

Uses memory mapped files in the default storage engine, which pushes the responsibility for memory management to the operating system