0
Getting Started with
MongoDB
Capital District Java Developers Network
January 16, 2014

Michael P. Redlich
@mpredli
about....
Who’s Mike?
• BS in CS from Rutgers University
• “Petrochemical Research Organization”
• Ai-Logix, Inc. (now AudioCodes)
•...
Upcoming Events
• Trenton Computer Festival
• March 14-15, 2014
• tcf-nj.org
• Emerging Technologies for the Enterprise
• ...
Upcoming Events

4
Friday, January 17, 14

4
Objectives
• What is MongoDB?
• What is NoSQL?
• Getting Started with MongoDB
• Basic CRUD Operations
• Live Demos (yea!)
...
What is MongoDB? (1)
• “...an open-source document database that

provides high performance, high availability, and
automa...
What is MongoDB? (2)
• “...an open-source database used by

companies of all sizes, across all industries and
for a wide v...
What is NoSQL?
• Developed to address shortcomings of a

traditional SQL relational database, namely:

• big data
• freque...
How is MongoDB
Used?

9
Friday, January 17, 14

9
Who is Using
MongoDB?

10
Friday, January 17, 14

10
Features of MongoDB
•

•
•
•
•

Document-Oriented
Storage

•
•

Full Index Support

•
•

Auto-Sharding

Replication and Hi...
Nomenclature (1)
RDBMS

MongoDB

Database

Database

Table

Collection

Row

Document

Index

Index

Join

Embedding & Lin...
Nomenclature (2)

13
Friday, January 17, 14

13
What is a Document?
• Basic unit of data
• analogous to a row in a RDBMS
• An ordered set of fields (keys) with

associated...
What is BSON?
• “...a binary-encoded serialization of JSON-like
documents.”

BSON Web Site, http://www.bsonspec.org/

• Bi...
What is a Collection?
• A group of documents
• analogous to a table in a RDBMS
• Schema-less
16
Friday, January 17, 14

16
Advantages of
Documents
• Documents correspond to native data
types in many programming languages

• Embedded documents an...
Document Structure
{

embedded document

lastName : “Redlich”,
firstName : “Michael”,
email : “mike@redlich.net”
role : {
...
Field Names
• Strings
• Cannot contain:
• null
• dots (.)
• dollar sign ($)
• No duplicate field names
19
Friday, January 1...
Conventions
• Command Prompt ($)
• MySQL prompt (mysql>)
• MongoDB prompt (>)
• Keywords (db, find(), etc.)
• Variables (v...
Example Database
• ACGNJ Board of Directors:
• lastName
• firstName
• roles (embedded documents)
• tenure
21
Friday, Januar...
Getting Started
• Download MongoDB
• Create a default data directory
•/data/db
•C:datadb
• Create your first MongoDB databa...
Starting MongoDB
• Start an instance of the MongoDB server:
$ mongod

• Start an instance of the MongoDB client (a
JavaScr...
Mongo Shell (1)
• Show the list of shell commands:
> help

• Show the list of databases:
> show dbs

• Show the current da...
Mongo Shell (2)
• Specify the database to use or create:
> use database

• Show the collections within the current
databas...
Mongo Shell (3)
• Show the recent system.profile
entries:

> show profile

• Tab completion
• Command history
26
Friday, J...
Primary Key
• Denoted by a special field, _id
• It can be generated:
• Implicitly:
{_id : ObjectID(value)}
•
• Explicitly:
...
ObjectIDs
• Default type for _id
• A 12-byte hexadecimal BSON type:

28
Friday, January 17, 14

28
Live Demo!

29
Friday, January 17, 14

29
Create

30
Friday, January 17, 14

30
Create a Database
• Create a database in MySQL:
mysql> CREATE DATABASE database;

• Create a database in MongoDB:
> use da...
Create a Collection
• Create a new table in MySQL:
mysql> CREATE TABLE table(column
datatype,...);

• Create a new collect...
Insert Data
• Insert a row in MySQL:
> INSERT INTO table(column,...)
VALUES(value,...);

• Insert a document in MongoDB:
>...
Insert Data with Loops
• Insert multiple documents with an array:
> for(int i = 0;i < j;++i)
db.collection.insert({field:a...
Live Demo!

35
Friday, January 17, 14

35
Read

36
Friday, January 17, 14

36
Query (1)
• Retrieve all rows in MySQL:
mysql> SELECT * FROM table;

• Retrieve all documents in MongoDB:
> db.collection....
Query (2)
• Retrieve specified columns in MySQL:
mysql> SELECT column1,column2 FROM
table;

• Retrieve specified fields in Mo...
Query (3)
• Retrieve specific rows in MySQL:
mysql> SELECT * FROM table WHERE
column = value;

• Retrieve specific documents...
Query (4)
• Retrieve specific rows in MySQL:
mysql> SELECT * FROM table WHERE
column = value ORDER BY value ASC;

• Retriev...
Query (5)
• Query for multiple documents (returns a
cursor):

> db.collection.find()

• Query for one document (returns a ...
Query Selectors
• Scalar:
• $ne, $mod, $exists, $type, $lt,
$lte, $gt, $gte

• Vector:
• $in, $nin, $all, $size
42
Friday,...
Query (6)
• Retrieve specific rows in MySQL:
mysql> SELECT * FROM table WHERE
column != value;

• Retrieve specific document...
Query (7)
• Retrieve specific rows in MySQL:
mysql> SELECT * FROM table WHERE
column1 = value OR column2 = value;

• Retrie...
Query (8)
> db.members.aggregate({$project:
{officer:"$roles.officer"}})

> db.members.find({tenure:
{$gt:ISODate("2014-12...
Query (9)
>
db.members.find({"roles.director":
{$all:["Director"]}})

>
db.members.find({"roles.committee":
{$in:["Histori...
Live Demo!

47
Friday, January 17, 14

47
Update

48
Friday, January 17, 14

48
Update (1)
• Update a row in MySQL:
mysql> UPDATE table SET column =
value WHERE id = id;

• Update a document in a MongoD...
Update (2)
• Update a row in MySQL:
mysql> UPDATE table SET column1 =
value WHERE column2 > value;

• Update a document in...
Update (3)
• Update a document using findOne():
> redlich =
db.members.findOne({lastName:
"Redlich"})
> redlich.roles = [{...
Atomic Update
Operators
• Scalar:
• $inc, $set, $unset
• Vector:
• $push, $pop, $pull, $pushAll,
$pullAll, $addToSet

52
F...
Update (4)
> db.members.update({lastName:
"Redlich"},{$set:
{"ISODate("2016-12-31")}})

> db.members.update({"roles.sig"},...
Delete

54
Friday, January 17, 14

54
Delete (1)
• Delete all rows in MySQL:
mysql> DELETE FROM table;

• Delete all documents in MongoDB:
> db.collection.remov...
Delete (2)
• Delete specific rows in MySQL:
mysql> DELETE FROM table WHERE
column = value;

• Delete specific documents in M...
Delete (2)
• Delete a MySQL database
mysql> DROP DATABASE database;

• Delete a MongoDB database
> use database
> db.dropD...
Backup/Restore

58
Friday, January 17, 14

58
Export (1)
• Export a collection to a JSON file
• Ensure mongod is running
$ mongoexport --db database -collection collecti...
Export (2)
• Export a collection to a CSV file
• Ensure mongod is running
• A list of fields is required
$ mongoexport --db ...
Import
• Import a collection from a JSON, CSV, or
TSV file

• Ensure mongod is running
$ mongoimport --db database -collect...
Dump
• Dump a specified MySQL database:
$ mysqldump -u root --opt database
> path.filename.sql

• Dump all MongoDB database...
Live Demo!

63
Friday, January 17, 14

63
Package Components
(1)
• Core Processes
• mongod - core DB process
• mongos - controller & query router
(sharding)

• mong...
Package Components
(2)
• Binary Import and Export
• mongodump - creates BSON dump files
• mongorestore - restores BSON dump...
Package Components
(3)
• Data Import and Export
• mongoimport - imports JSON, CSV, or
TSV data formats

• mongoexport - ex...
Package Components
(4)

• Diagnostic Tools
• mongostat - captures database

operations by type (insert, query, etc.)

• mo...
Package Components
(5)
• GridFS
• mongofiles - provides a commandline interaction to a GridFS storage
system

68
Friday, J...
MongoDB Resources
(1)

69
Friday, January 17, 14

69
MongoDB Resources
(2)

• mongodb.org
• docs.mongodb.org
• mongodb.org/books
• mongodb.com/products/mongodb
• mongodb.com/r...
Thanks!
mike@redlich.net
@mpredli
javasig.org

71
Friday, January 17, 14

71
Upcoming SlideShare
Loading in...5
×

Getting Started with MongoDB

1,303

Published on

This is a presentation on how to get started with the MongoDB database available at http://www.mongodb.org/.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,303
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
81
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "Getting Started with MongoDB"

  1. 1. Getting Started with MongoDB Capital District Java Developers Network January 16, 2014 Michael P. Redlich @mpredli about.me/mpredli/ 1 Friday, January 17, 14 1
  2. 2. Who’s Mike? • BS in CS from Rutgers University • “Petrochemical Research Organization” • Ai-Logix, Inc. (now AudioCodes) • Amateur Computer Group of New Jersey • Publications • Presentations 2 Friday, January 17, 14 2
  3. 3. Upcoming Events • Trenton Computer Festival • March 14-15, 2014 • tcf-nj.org • Emerging Technologies for the Enterprise • April 22-23, 2014 • phillyemergingtech.com 3 Friday, January 17, 14 3
  4. 4. Upcoming Events 4 Friday, January 17, 14 4
  5. 5. Objectives • What is MongoDB? • What is NoSQL? • Getting Started with MongoDB • Basic CRUD Operations • Live Demos (yea!) • MongoDB Resources 5 Friday, January 17, 14 5
  6. 6. What is MongoDB? (1) • “...an open-source document database that provides high performance, high availability, and automatic scaling.” MongoDB Web Site, http://www.mongodb.org/ • It’s name derived from “humongous” • Written in C++ 6 Friday, January 17, 14 6
  7. 7. What is MongoDB? (2) • “...an open-source database used by companies of all sizes, across all industries and for a wide variety of applications. It is an agile database that allows schemas to change quickly as applications evolve, while still providing functionality developers expect from traditional databases...” MongoDB Products Web Site, http://www.mongodb.com/products/mongodb/ 7 Friday, January 17, 14 7
  8. 8. What is NoSQL? • Developed to address shortcomings of a traditional SQL relational database, namely: • big data • frequency of access to big data • performance and scalability 8 Friday, January 17, 14 8
  9. 9. How is MongoDB Used? 9 Friday, January 17, 14 9
  10. 10. Who is Using MongoDB? 10 Friday, January 17, 14 10
  11. 11. Features of MongoDB • • • • • Document-Oriented Storage • • Full Index Support • • Auto-Sharding Replication and High Availability Fast In-Place Updates Map/Reduce GridFS Professional Support by MongoDB Querying 11 Friday, January 17, 14 11
  12. 12. Nomenclature (1) RDBMS MongoDB Database Database Table Collection Row Document Index Index Join Embedding & Linking Foreign Key Reference 12 Friday, January 17, 14 12
  13. 13. Nomenclature (2) 13 Friday, January 17, 14 13
  14. 14. What is a Document? • Basic unit of data • analogous to a row in a RDBMS • An ordered set of fields (keys) with associated values stored in BSON format • similar to JSON 14 Friday, January 17, 14 14
  15. 15. What is BSON? • “...a binary-encoded serialization of JSON-like documents.” BSON Web Site, http://www.bsonspec.org/ • Binary JSON • Designed to be lightweight, traversable, and efficient 15 Friday, January 17, 14 15
  16. 16. What is a Collection? • A group of documents • analogous to a table in a RDBMS • Schema-less 16 Friday, January 17, 14 16
  17. 17. Advantages of Documents • Documents correspond to native data types in many programming languages • Embedded documents and arrays reduce the need for expensive joins • Dynamic schema support fluent polymorphism 17 Friday, January 17, 14 17
  18. 18. Document Structure { embedded document lastName : “Redlich”, firstName : “Michael”, email : “mike@redlich.net” role : { officer : “President”, field sig : “Java Users Group” value } } 18 Friday, January 17, 14 18
  19. 19. Field Names • Strings • Cannot contain: • null • dots (.) • dollar sign ($) • No duplicate field names 19 Friday, January 17, 14 19
  20. 20. Conventions • Command Prompt ($) • MySQL prompt (mysql>) • MongoDB prompt (>) • Keywords (db, find(), etc.) • Variables (variable) 20 Friday, January 17, 14 20
  21. 21. Example Database • ACGNJ Board of Directors: • lastName • firstName • roles (embedded documents) • tenure 21 Friday, January 17, 14 21
  22. 22. Getting Started • Download MongoDB • Create a default data directory •/data/db •C:datadb • Create your first MongoDB database 22 Friday, January 17, 14 22
  23. 23. Starting MongoDB • Start an instance of the MongoDB server: $ mongod • Start an instance of the MongoDB client (a JavaScript-based shell): $ mongo 23 Friday, January 17, 14 23
  24. 24. Mongo Shell (1) • Show the list of shell commands: > help • Show the list of databases: > show dbs • Show the current database: > db 24 Friday, January 17, 14 24
  25. 25. Mongo Shell (2) • Specify the database to use or create: > use database • Show the collections within the current database: > show collections • Show the users within the database: > show users 25 Friday, January 17, 14 25
  26. 26. Mongo Shell (3) • Show the recent system.profile entries: > show profile • Tab completion • Command history 26 Friday, January 17, 14 26
  27. 27. Primary Key • Denoted by a special field, _id • It can be generated: • Implicitly: {_id : ObjectID(value)} • • Explicitly: • {_id : 2 }, { _id : “MPR”} 27 Friday, January 17, 14 27
  28. 28. ObjectIDs • Default type for _id • A 12-byte hexadecimal BSON type: 28 Friday, January 17, 14 28
  29. 29. Live Demo! 29 Friday, January 17, 14 29
  30. 30. Create 30 Friday, January 17, 14 30
  31. 31. Create a Database • Create a database in MySQL: mysql> CREATE DATABASE database; • Create a database in MongoDB: > use database 31 Friday, January 17, 14 31
  32. 32. Create a Collection • Create a new table in MySQL: mysql> CREATE TABLE table(column datatype,...); • Create a new collection in MongoDB: > db.collection.insert({field:value,. ..}) 32 Friday, January 17, 14 32
  33. 33. Insert Data • Insert a row in MySQL: > INSERT INTO table(column,...) VALUES(value,...); • Insert a document in MongoDB: > db.collection.insert({field:value,. ..}) 33 Friday, January 17, 14 33
  34. 34. Insert Data with Loops • Insert multiple documents with an array: > for(int i = 0;i < j;++i) db.collection.insert({field:array[i ]}); • Insert multiple documents with variable: > for(int i = 0;i < j;++i) db.collection.insert({field:i}) 34 Friday, January 17, 14 34
  35. 35. Live Demo! 35 Friday, January 17, 14 35
  36. 36. Read 36 Friday, January 17, 14 36
  37. 37. Query (1) • Retrieve all rows in MySQL: mysql> SELECT * FROM table; • Retrieve all documents in MongoDB: > db.collection.find() 37 Friday, January 17, 14 37
  38. 38. Query (2) • Retrieve specified columns in MySQL: mysql> SELECT column1,column2 FROM table; • Retrieve specified fields in MongoDB: > db.collection.find({}, {field1:true,field2:true}) 38 Friday, January 17, 14 38
  39. 39. Query (3) • Retrieve specific rows in MySQL: mysql> SELECT * FROM table WHERE column = value; • Retrieve specific documents in MongoDB: > db.collection.find({field:value}) 39 Friday, January 17, 14 39
  40. 40. Query (4) • Retrieve specific rows in MySQL: mysql> SELECT * FROM table WHERE column = value ORDER BY value ASC; • Retrieve specific documents in MongoDB: > db.collection.find({field:value}).s ort({field:1}) 40 Friday, January 17, 14 40
  41. 41. Query (5) • Query for multiple documents (returns a cursor): > db.collection.find() • Query for one document (returns a single document): > db.collection.findOne() 41 Friday, January 17, 14 41
  42. 42. Query Selectors • Scalar: • $ne, $mod, $exists, $type, $lt, $lte, $gt, $gte • Vector: • $in, $nin, $all, $size 42 Friday, January 17, 14 42
  43. 43. Query (6) • Retrieve specific rows in MySQL: mysql> SELECT * FROM table WHERE column != value; • Retrieve specific documents in MongoDB: > db.collection.find({field: {$ne:value}}) 43 Friday, January 17, 14 43
  44. 44. Query (7) • Retrieve specific rows in MySQL: mysql> SELECT * FROM table WHERE column1 = value OR column2 = value; • Retrieve specific documents in MongoDB: > db.collection.find({$or: [{field:value},{field:value}]) 44 Friday, January 17, 14 44
  45. 45. Query (8) > db.members.aggregate({$project: {officer:"$roles.officer"}}) > db.members.find({tenure: {$gt:ISODate("2014-12-31")}}) > db.members.find({"roles.officer": {$exists:true}}).sort({"roles.offic er":1}) 45 Friday, January 17, 14 45
  46. 46. Query (9) > db.members.find({"roles.director": {$all:["Director"]}}) > db.members.find({"roles.committee": {$in:["Historian","Newsletter"]}}) > db.members.find({roles:{$size: 3}}) 46 Friday, January 17, 14 46
  47. 47. Live Demo! 47 Friday, January 17, 14 47
  48. 48. Update 48 Friday, January 17, 14 48
  49. 49. Update (1) • Update a row in MySQL: mysql> UPDATE table SET column = value WHERE id = id; • Update a document in a MongoDB: > db.collection.update({_id:value}, {$set:{field:value}},{multi:true}) 49 Friday, January 17, 14 49
  50. 50. Update (2) • Update a row in MySQL: mysql> UPDATE table SET column1 = value WHERE column2 > value; • Update a document in MongoDB: > db.collection.update({field1: {$gt:value}},{$set:{field2:value}}, {multi:true}) 50 Friday, January 17, 14 50
  51. 51. Update (3) • Update a document using findOne(): > redlich = db.members.findOne({lastName: "Redlich"}) > redlich.roles = [{sig:"Java Users Group"}] > db.members.update({lastName: "Redlich"},redlich) 51 Friday, January 17, 14 51
  52. 52. Atomic Update Operators • Scalar: • $inc, $set, $unset • Vector: • $push, $pop, $pull, $pushAll, $pullAll, $addToSet 52 Friday, January 17, 14 52
  53. 53. Update (4) > db.members.update({lastName: "Redlich"},{$set: {"ISODate("2016-12-31")}}) > db.members.update({"roles.sig"}, {$set:{"roles.sig":"JUG"}}) 53 Friday, January 17, 14 53
  54. 54. Delete 54 Friday, January 17, 14 54
  55. 55. Delete (1) • Delete all rows in MySQL: mysql> DELETE FROM table; • Delete all documents in MongoDB: > db.collection.remove() 55 Friday, January 17, 14 55
  56. 56. Delete (2) • Delete specific rows in MySQL: mysql> DELETE FROM table WHERE column = value; • Delete specific documents in MongoDB: > db.collection.remove({field:value}) 56 Friday, January 17, 14 56
  57. 57. Delete (2) • Delete a MySQL database mysql> DROP DATABASE database; • Delete a MongoDB database > use database > db.dropDatabase() 57 Friday, January 17, 14 57
  58. 58. Backup/Restore 58 Friday, January 17, 14 58
  59. 59. Export (1) • Export a collection to a JSON file • Ensure mongod is running $ mongoexport --db database -collection collection --out path/ filename.json 59 Friday, January 17, 14 59
  60. 60. Export (2) • Export a collection to a CSV file • Ensure mongod is running • A list of fields is required $ mongoexport --db database -collection collection --fields field1,field2,... --csv --out path/ filename.json 60 Friday, January 17, 14 60
  61. 61. Import • Import a collection from a JSON, CSV, or TSV file • Ensure mongod is running $ mongoimport --db database -collection collection < path/ filename.json 61 Friday, January 17, 14 61
  62. 62. Dump • Dump a specified MySQL database: $ mysqldump -u root --opt database > path.filename.sql • Dump all MongoDB databases: • Ensure mongod is not running $ mongodump --dbpath /data/db --out path 62 Friday, January 17, 14 62
  63. 63. Live Demo! 63 Friday, January 17, 14 63
  64. 64. Package Components (1) • Core Processes • mongod - core DB process • mongos - controller & query router (sharding) • mongo - interactive JavaScript-based shell 64 Friday, January 17, 14 64
  65. 65. Package Components (2) • Binary Import and Export • mongodump - creates BSON dump files • mongorestore - restores BSON dump files • bsondump - converts BSON to JSON • mongooplog - streams oplog entries 65 Friday, January 17, 14 65
  66. 66. Package Components (3) • Data Import and Export • mongoimport - imports JSON, CSV, or TSV data formats • mongoexport - exports to JSON, CSV, or TSV data formats 66 Friday, January 17, 14 66
  67. 67. Package Components (4) • Diagnostic Tools • mongostat - captures database operations by type (insert, query, etc.) • mongotop - tracks read/write activity • mongosniff - provides tracing/sniffing view into database activity • mongoperf - performance testing tool 67 Friday, January 17, 14 67
  68. 68. Package Components (5) • GridFS • mongofiles - provides a commandline interaction to a GridFS storage system 68 Friday, January 17, 14 68
  69. 69. MongoDB Resources (1) 69 Friday, January 17, 14 69
  70. 70. MongoDB Resources (2) • mongodb.org • docs.mongodb.org • mongodb.org/books • mongodb.com/products/mongodb • mongodb.com/reference • bsonspec.org • education.mongodb.com 70 Friday, January 17, 14 70
  71. 71. Thanks! mike@redlich.net @mpredli javasig.org 71 Friday, January 17, 14 71
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×