SlideShare une entreprise Scribd logo
1  sur  66
MongoDB - Basics
Apr - 2013
cm@paybook.com
Friday, May 24, 13
Overview
MongoDB is a document database that provides high performance, high
availability, and easy scalability.
• Document Database
◦ Documents (objects) map nicely to programming language data types.
◦ Embedded documents and arrays reduce need for joins.
◦ Dynamic schema makes polymorphism easier.
• High Performance
◦ Embedding makes reads and writes fast.
◦ Indexes can include keys from embedded documents and arrays.
◦ Optional streaming writes (no acknowledgments).
• High Availability
◦ Replicated servers with automatic master failover.
• Easy Scalability
◦ Automatic sharding distributes collection data across machines.
◦ Eventually-consistent reads can be distributed over replicated servers
Friday, May 24, 13
A MongoDB deployment hosts a number of databases.A database holds
a set of collections.A collection holds a set of documents.A document is
a set of key-value pairs. Documents have dynamic schema. Dynamic
schema means that documents in the same collection do not need to
have the same set of fields or structure, and common fields in a
collection’s documents may hold different types of data.
Mongo Data Model
Databases
Collections
Documents
Host
Friday, May 24, 13
Queries
Like others databases engines MongoDB
supports different kind of queries.
• Find
• Insert
• Update
• Delete
Friday, May 24, 13
Deployment
MongoDB has the installing capability with the following
configuration.
• Standalone (Single-instance).
• Replica sets, high performance replication with
automated failover.
• Shared clusters, partition large data sets over
many machines, transparently to the users
(horizontal scalability)
Friday, May 24, 13
Technical Facts
• MongoDB is a server process that runs on Linux,Windows and
OS X. It can be run both as a 32 or 64-bit application.We
recommend running in 64-bit mode, since MongoDB is limited
to a total data size of about 2GB for all databases in 32-bit
mode.
• The MongoDB process listens on port 27017 by default.
• Clients connect to the MongoDB process, optionally authenticate
themselves if security is turned on.
• MongoDB stores its data in files (default location is /data/db/),
and uses memory mapped files for data management for
efficiency.
Friday, May 24, 13
NoSQL
A NoSQL database provides a mechanism for storage and retrieval
of data that use looser consistency models than traditional relational
databases in order to achieve horizontal scaling and higher availability.
• Features.
• Dynamic Schemas (Schemaless).
• Auto-replication and sharding.
• Integrated cache
• Speed
Friday, May 24, 13
NoSQL MongoDB
Friday, May 24, 13
Key–value stores allow the application to store its data in a schema-
less way.The data could be stored in a datatype of a programming
language or an object. Because of this, there is no need for a fixed
data model.
A schemaless database allows any data, structured with individual
fields and structures, to be stored in the database.
Being schemaless reduces ceremony (you don't have to define
schemas) and increases flexibility (you can store all sorts of data
without prior definition).
Schema-less
Friday, May 24, 13
Pros
• The data structures that you design on your programming language
are mapped into the database.
• ALTER TABLE commands are no longer required.
Cons
• Not designing the data model schema at the first stage can lead to
weak or inconsistent data model in later stage of the application.
• You may eventually duplicate the schema across applications.
Schema-less
Friday, May 24, 13
JavaScript
• JavaScript (JS) is an interpreted computer programming
language. It was originally implemented as part of web
browsers so that client-side scripts could interact with the
user, control the browser, communicate asynchronously, and
alter the document content that was displayed.
• JavaScript's use in applications outside of web pages—for
example, in PDF documents, site-specific browsers, and desktop
widgets—is also significant. Newer and faster JavaScriptVMs and
frameworks built upon them (notably Node.js) have also
increased the popularity of JavaScript for server-side web
applications.
Friday, May 24, 13
JavaScript & MongoDB
• In earlier versions was based on SpiderMonkey engine.
• No in 2.4 version MongoDB is based on a JavaScript engine
calledV8.
• Improved concurrency for JavaScript operations,
• Modernized JavaScript implementation, and
• Removed non-standard SpiderMonkey features
Friday, May 24, 13
JSON
• JavaScript Object Notation
• Is a lightweight data-interchange format.
• It is easy for humans to read and write.
• It is easy for machines to parse and generate.
• Is a text format that is completely language independent but uses
conventions that are familiar to programmers of the C-family of
languages.
Friday, May 24, 13
JSON
JSON is built on two structures:
• A collection of name/value pairs. In various languages, this is realized as an
object, record, struct, dictionary, hash table, keyed list, or associative array.
• An ordered list of values. In most languages, this is realized as an array,
vector, list, or sequence.
Friday, May 24, 13
JSON
Object Array
Friday, May 24, 13
JSON
Object/Arrays
Friday, May 24, 13
BSON
A serialization format used to store
documents and make remote procedure calls
in MongoDB.“BSON” is a portmanteau of the
words “binary” and “JSON”.Think of BSON as
a binary representation of JSON (JavaScript
Object Notation) documents. For a detailed
spec, see bsonspec.org.
Friday, May 24, 13
BSON Data types
Type Type
Double Regular expression
String JavaScript
Object Symbol
Array 32-bit integer
Binary data Timestamp
Object ID 64-bit integer
Boolean Min key
Date Max key
Null
Friday, May 24, 13
Drivers
• Are available for the following languages.
C Node.js*
C++ Perl
C# PHP
Erlang Python
Java Ruby
JavaScript Scala
* Node.js based on JavaScript
Friday, May 24, 13
Drivers
http://docs.mongodb.org/ecosystem/drivers/
Friday, May 24, 13
Installing MongoDB
• Windows - http://docs.mongodb.org/manual/
tutorial/install-mongodb-on-windows/
• Mac - http://docs.mongodb.org/manual/
tutorial/install-mongodb-on-os-x/
• Linux - http://docs.mongodb.org/manual/
tutorial/install-mongodb-on-linux/
Friday, May 24, 13
Mongo Shell
The mongo shell is an
interactive JavaScript shell for
MongoDB, and is part of all
MongoDB distributions.
Friday, May 24, 13
Workshop
1. Debian linux virtual machine installed on virtualbox
environment.
2. Start the virtual machine
3.The data access to the virtual machine is
user: root
password: mongodb2013
Friday, May 24, 13
Mongo shell data types
MongoDB BSON provide support for additional data types than JSON.
Drivers provide native support for these data types in host languages
and the mongo shell also provides several helper classes to support the
use of these data types in the mongo JavaScript shell. See MongoDB
Extended JSON for additional information.
• Date
• ObjectId
• NumberLong
Friday, May 24, 13
• To access to Mongo shell just type “mongo”.
Mongo shell
Friday, May 24, 13
Mongo shell
• To access to Mongo on other host shell just
type “mongo host/database”.
Friday, May 24, 13
Mongo shell command
helpers
Friday, May 24, 13
CRUD
In computer programming, create, read, update and delete (CRUD) are the four basic
functions of persistent storage. Sometimes CRUD is expanded with the words retrieve
instead of read, modify instead of update, or destroy instead of delete. It is also
sometimes used to describe user interface conventions that facilitate viewing,
searching, and changing information; often using computer-based forms and reports.
The acronym CRUD refers to all of the major functions that are implemented in
relational database applications. Each letter in the acronym can map to a standard SQL
statement and HTTP method:
Making full use of HTTP methods, along with other constraints, is considered "RESTful".
Friday, May 24, 13
Mongo CRUD
Operations
• Create
• Are those that add new records or documents to a collection in MongoDB.
• insert()
• update()
• Read
• Are those that retrieve records or documents from a collection in
MongoDB
• find()
• findOne()
Friday, May 24, 13
Mongo CRUD
Operations
• Update
• Are those that modify existing records or documents in a
MongoDB collection
• update()
• Delete
• Are those that remove documents from a collection in
MongoDB
• remove()
Friday, May 24, 13
Create
The insert() method inserts a document or documents into a
collection.
Consider the following behaviors of the insert() method:
• If the collection does not exist, then the insert() method will
create the collection.
• If the document does not specify an _id field, then MongoDB
will add the _id field and assign a unique ObjectId for the
document before inserting.
• If the document specifies a new field, then the insert()
method inserts the document with the new field.
Friday, May 24, 13
Create
The insert() method takes one of the following parameters:
• document – A document to insert into the collection.
db.products.insert( { item: "card", qty: 15 } )
This operation inserts a new document into the products
collection with the item field set to card, the qty field set to
15, and the _id field set to a unique ObjectId:
{ "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "card", "qty" : 15 }
Friday, May 24, 13
Create
To insert a single document, with a custom _id field, include
the _id field set to a unique identifier and pass the document
to the insert() method as follows:
db.products.insert( { _id: 10, item: "box", qty: 20 } )
This operation inserts a new document in the products
collection with the _id field set to 10, the item field set to box,
the qty field set to 20:
{ "_id" : 10, "item" : "box", "qty" : 20 }
Friday, May 24, 13
Create
To insert multiple documents, pass an array of documents to
the insert() method as in the following:
db.products.insert( [ { _id: 11, item: "pencil", qty: 50, type: "no.2" },
{ item: "pen", qty: 20 },
{ item: "eraser", qty: 25 } ] )
Friday, May 24, 13
Create
The operation will insert three documents into the products
collection:
• A document with the fields _id set to 11, item set to pencil, qty
set to 50, and the type set to no.2.
• A document with the fields _id set to a unique objectid, item
set to pen, and qty set to 20.
• A document with the fields _id set to a unique objectid, item
set to eraser, and qty set to 25.
Friday, May 24, 13
Create
{ "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" }
{ "_id" : ObjectId("50631bc0be4617f17bb159ca"), "item" : "pen", "qty" : 20 }
{ "_id" : ObjectId("50631bc0be4617f17bb159cb"), "item" : "eraser", "qty" : 25 }
Friday, May 24, 13
Exercise
1. Use the enoan database
2. Execute the following commands.
- db.products.insert({item:"card", qty:15});
- db.products.insert({_id:10, item:"box", qty:20});
- db.products.insert([{ _id:11, item:"pencil", qty:50, type:"no.
2"},{item:"pen", qty:20},{item:"eraser", qty:25}]);
Friday, May 24, 13
Read
The command to read data in a collection is
find(query,projection).
The syntax to use this command is
db.collection.find()
When the collection has a lot of documents the
find automatically split the result in packages of
20 documents.
Friday, May 24, 13
Read
Sometimes we need to count the number of
documents on a collection with or without
query filter.
db.collection.find().count()
Friday, May 24, 13
Read
Sort documents
db.collection.find().sort()
Limit documents
db.collection.find().limit()
Friday, May 24, 13
Read
Find one document
db.collection.findOne()
Format the result
db.collection.find().pretty()
Friday, May 24, 13
Exercise
1. In the enoan database find all the documents
on the zips collection.
1.1 Connect to enoan database using
mongo shell
1.2 Execute:
db.zips.find()
Friday, May 24, 13
Exercise
Friday, May 24, 13
Read
The command find has the capability of query documents with a
condition. Also has the option to project the results of some keys.
The method takes the following parameters.
query. Optional. Specifies the selection criteria using query
operators. Omit the query parameter or pass an empty document
(e.g. {}) to return all documents in the collection.
projection. Optional. Controls the fields to return, or the
projection.The _id key is always returned you must to ignore this
key to hidde it.
Friday, May 24, 13
Read
Some samples with zips collection.
db.zips.find()
Return all the information on the collection.
db.zips.find({"state":"TX"})
Return all the documents where the state is equal to TX (Texas)
db.zips.find({"state":"TX"},{"city":1,"state":1})
Return all the documents where the state is equal to TX (Texas)
Shows only state and city keys
Friday, May 24, 13
Read
Also we can use selection criteria in our queries.
$gt. Greater than operator
$gte. Greater than or equal operator
$lt. Lower than operator
$lte. Lower than or equal operator
db.zips.find({"pop":{$gt:100000}})
Return all the documents where the pop key is greater than 100,000
db.zips.find({"pop":{$lt:5}})
Friday, May 24, 13
Update
The update() method modifies an existing document
or documents in a collection. By default the update()
method updates a single document.To update all
documents in the collection that match the update
query criteria, specify the multi option.To insert a
document if no document matches the update query
criteria, specify the upsert option.
Friday, May 24, 13
Update
The update() method takes the following parameters:
• query (document). Specifies the selection criteria for the
update.The query parameter employs the same query selectors
as used in the db.collection.find() method.
• update (document). Specifies the modifications to apply.
• upsert (boolean). Optional. Specifies an upsert operation
• multi (boolean). Optional. Specifies whether to update multiple
documents that meet the query criteria.
Friday, May 24, 13
Update
Some notes about the upsert
• The default value is false.When true, the update() method will update
an existing document that matches the query selection criteria or if
no document matches the criteria, insert a new document with the
fields and values of the update parameter and if the update included
only update operators, the query parameter as well.
Some notes about the multi
• When not specified, the default value is false and the update() method
updates a single document that meet the query criteria.
• When true, the update() method updates all documents that meet
the query criteria.
Friday, May 24, 13
Update
update() field operators
$inc. increments a value of a field by a specified amount.
If the field does not exist, $inc sets the field to the
specified amount. $inc accepts positive and negative
incremental amounts.
db.collection.update( { field: value },{ $inc: { field1: amount } } );
db.collection.update( { age: 20 }, { $inc: { age: 1 } });
Friday, May 24, 13
Update
update() field operators
$rename. updates the name of a field.The new field name
must differ from the existing field name.
{$rename: { <old name1>: <new name1>, <old name2>: <new
name2>, ... } }
db.students.update( { _id: 1 }, { $rename: { 'nickname': 'alias',
'cell': 'mobile' } } )
Friday, May 24, 13
Update
update() field operators
$set. set a particular value
db.collection.update( { field: value1 }, { $set: { field1: value2 } } );
This statement updates in the document in collection
where field matches value1 by replacing the value of the
field field1 with value2.This operator will add the
specified field or fields if they do not exist in this
document or replace the existing value of the specified
field(s) if they already exist.
Friday, May 24, 13
Update
update() field operators
$unset. deletes a particular field
db.collection.update( { field: value1 }, { $unset: { field1: "" } } );
The above example deletes field1 in collection from documents
where field has a value of value1.The value of the field in the
$unset statement (i.e. "" above) does not impact the operation.
If documents match the initial query (e.g. { field: value1 } above)
but do not have the field specified in the $unset operation (e.g.
field1), then the statement has no effect on the document.
Friday, May 24, 13
Exercise
1. Update the product collection add 20 to qty only on the item
named card.
2. Update the product collection change the name of the item
box to boxes.
3. Update all the documents on the product collection add the
key status with value 1.
4. Update all the documents on the product collection change
the key qty to quantity.
Friday, May 24, 13
Remove
The remove method removes documents from a collection.
The remove() method can take the following parameters:
• query (document) – Optional. Specifies the deletion criteria
using query operators. Omit the query parameter or pass an
empty document (e.g. {} ) to delete all documents in the
collection.
• justOne (boolean) – Optional.A boolean that limits the
deletion to just one document.The default value is false. Set to
true to delete only the first result.
Friday, May 24, 13
Remove
Consider the following examples of the remove method.The remove() method can
take the following parameters:
• To remove all documents in a collection, call the remove method with no
parameters:
db.products.remove()
• To remove the documents that match a deletion criteria, call the remove method
with the query criteria:
db.products.remove( { qty: { $gt: 20 } } )
• To remove the first document that match a deletion criteria, call the remove method
with the query criteria and the justOne parameter set to true or 1:
db.products.remove( { qty: { $gt: 20 } }, true )
Friday, May 24, 13
Exercise
1. Remove the item on the product collection where _id is equal
to 10.
2. Remove all the items on the zips collection where the pop are
lower than or equal 1.
Friday, May 24, 13
PHP Mongodb
Friday, May 24, 13
Python Mongodb
Friday, May 24, 13
Security
Strategies for Reducing Risk
The most effective way to reduce risk for MongoDB deployments is to run
your entire MongoDB deployment, including all MongoDB components (i.e.
mongod, mongos and application instances) in a trusted environment.Trusted
environments use the following strategies to control access:
• Network filter (e.g. firewall) rules that block all connections from unknown
systems to MongoDB components.
• Bind mongod and mongos instances to specific IP addresses to limit
accessibility.
• Limit MongoDB programs to non-public local networks, and virtual private
networks.
Friday, May 24, 13
Security
Strategies for Reducing Risk
You may further reduce risk by:
• Requiring authentication for access to MongoDB instances.
• Requiring strong, complex, single purpose authentication credentials.This should
be part of your internal security policy but is not currently configurable in
MongoDB.
• Deploying a model of least privilege, where all users have only the amount of
access they need to accomplish required tasks, and no more.
• Following the best application development and deployment practices, which
includes: validating all inputs, managing sessions, and application-level access
control.
Friday, May 24, 13
Replication
Database replication ensures redundancy, backup, and automatic
failover. Replication occurs through groups of servers known as
replica sets.
A MongoDB replica set is a cluster of mongod instances that
replicate amongst one another and ensure automated failover.
Most replica sets consist of two or more mongod instances with
at most one of these designated as the primary and the rest as
secondary members. Clients direct all writes to the primary,
while the secondary members replicate from the primary
asynchronously.
Friday, May 24, 13
Replication
Friday, May 24, 13
Sharding
Sharding distributes a single logical database system across a
cluster of machines.
Sharding is MongoDB’s approach to scaling out. Sharding partitions
a collection and stores the different portions on different
machines.When a database’s collections become too large for
existing storage, you need only add a new machine. Sharding
automatically distributes collection data to the new server.
Sharding automatically balances data and load across machines.
Sharding provides additional write capacity by distributing the
write load over a number of mongod instances. Sharding allows
users to increase the potential amount of data in the working set.
Friday, May 24, 13
Sharding
Friday, May 24, 13
References
• Mongodb http://mongodb.org/
• 10gen http://10gen.com
• JSON http://json.org
• BSON http://bsonspec.org/
• Mongo DB Drivers http://docs.mongodb.org/ecosystem/drivers/
• PHP mongodb driver https://github.com/mongodb/mongo-php-driver
• Python mongodb (Pymongo) driver http://api.mongodb.org/python/
current/installation.html
Friday, May 24, 13

Contenu connexe

Tendances (20)

Mongo DB 102
Mongo DB 102Mongo DB 102
Mongo DB 102
 
Mongo db workshop # 01
Mongo db workshop # 01Mongo db workshop # 01
Mongo db workshop # 01
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
 
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorialsMongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
 
MongoDB
MongoDBMongoDB
MongoDB
 
Mongo DB
Mongo DB Mongo DB
Mongo DB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Mongo db
Mongo dbMongo db
Mongo db
 
Top 10 frameworks of node js
Top 10 frameworks of node jsTop 10 frameworks of node js
Top 10 frameworks of node js
 
Mongodb introduction and_internal(simple)
Mongodb introduction and_internal(simple)Mongodb introduction and_internal(simple)
Mongodb introduction and_internal(simple)
 
Mongo db
Mongo dbMongo db
Mongo db
 
MongoDB
MongoDBMongoDB
MongoDB
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB 101
MongoDB 101MongoDB 101
MongoDB 101
 
Mongo db report
Mongo db reportMongo db report
Mongo db report
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Mongo db workshop # 02
Mongo db workshop # 02Mongo db workshop # 02
Mongo db workshop # 02
 

En vedette

Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMetatagg Solutions
 
MongoD Essentials
MongoD EssentialsMongoD Essentials
MongoD Essentialszahid-mian
 
Intro to NoSQL and MongoDB
Intro to NoSQL and MongoDBIntro to NoSQL and MongoDB
Intro to NoSQL and MongoDBDATAVERSITY
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDBAlex Sharp
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBRavi Teja
 

En vedette (8)

Pdf almas
Pdf almasPdf almas
Pdf almas
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg Solutions
 
MongoD Essentials
MongoD EssentialsMongoD Essentials
MongoD Essentials
 
Mongo db
Mongo dbMongo db
Mongo db
 
Intro to NoSQL and MongoDB
Intro to NoSQL and MongoDBIntro to NoSQL and MongoDB
Intro to NoSQL and MongoDB
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 

Similaire à Mongo db basics

Introduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesIntroduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesAshishRathore72
 
Introduction to MongoDB Basics from SQL to NoSQL
Introduction to MongoDB Basics from SQL to NoSQLIntroduction to MongoDB Basics from SQL to NoSQL
Introduction to MongoDB Basics from SQL to NoSQLMayur Patil
 
MongoDB NoSQL database a deep dive -MyWhitePaper
MongoDB  NoSQL database a deep dive -MyWhitePaperMongoDB  NoSQL database a deep dive -MyWhitePaper
MongoDB NoSQL database a deep dive -MyWhitePaperRajesh Kumar
 
MongoDB.local Sydney: An Introduction to Document Databases with MongoDB
MongoDB.local Sydney: An Introduction to Document Databases with MongoDBMongoDB.local Sydney: An Introduction to Document Databases with MongoDB
MongoDB.local Sydney: An Introduction to Document Databases with MongoDBMongoDB
 
how_can_businesses_address_storage_issues_using_mongodb.pdf
how_can_businesses_address_storage_issues_using_mongodb.pdfhow_can_businesses_address_storage_issues_using_mongodb.pdf
how_can_businesses_address_storage_issues_using_mongodb.pdfsarah david
 
SQL vs NoSQL, an experiment with MongoDB
SQL vs NoSQL, an experiment with MongoDBSQL vs NoSQL, an experiment with MongoDB
SQL vs NoSQL, an experiment with MongoDBMarco Segato
 
Copy of MongoDB .pptx
Copy of MongoDB .pptxCopy of MongoDB .pptx
Copy of MongoDB .pptxnehabsairam
 
how_can_businesses_address_storage_issues_using_mongodb.pptx
how_can_businesses_address_storage_issues_using_mongodb.pptxhow_can_businesses_address_storage_issues_using_mongodb.pptx
how_can_businesses_address_storage_issues_using_mongodb.pptxsarah david
 
Accra MongoDB User Group
Accra MongoDB User GroupAccra MongoDB User Group
Accra MongoDB User GroupMongoDB
 
MongoDB NoSQL - Developer Guide
MongoDB NoSQL - Developer GuideMongoDB NoSQL - Developer Guide
MongoDB NoSQL - Developer GuideShiv K Sah
 
Mongo db halloween party
Mongo db halloween partyMongo db halloween party
Mongo db halloween partyAndrea Balducci
 
Mongo db transcript
Mongo db transcriptMongo db transcript
Mongo db transcriptfoliba
 
Big Data, NoSQL with MongoDB and Cassasdra
Big Data, NoSQL with MongoDB and CassasdraBig Data, NoSQL with MongoDB and Cassasdra
Big Data, NoSQL with MongoDB and CassasdraBrian Enochson
 
Jumpstart: Building Your First MongoDB App
Jumpstart: Building Your First MongoDB AppJumpstart: Building Your First MongoDB App
Jumpstart: Building Your First MongoDB AppMongoDB
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentationHyphen Call
 

Similaire à Mongo db basics (20)

Mongo db
Mongo dbMongo db
Mongo db
 
Introduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesIntroduction to MongoDB and its best practices
Introduction to MongoDB and its best practices
 
Mongodb
MongodbMongodb
Mongodb
 
Introduction to MongoDB Basics from SQL to NoSQL
Introduction to MongoDB Basics from SQL to NoSQLIntroduction to MongoDB Basics from SQL to NoSQL
Introduction to MongoDB Basics from SQL to NoSQL
 
MongoDB NoSQL database a deep dive -MyWhitePaper
MongoDB  NoSQL database a deep dive -MyWhitePaperMongoDB  NoSQL database a deep dive -MyWhitePaper
MongoDB NoSQL database a deep dive -MyWhitePaper
 
MongoDB.local Sydney: An Introduction to Document Databases with MongoDB
MongoDB.local Sydney: An Introduction to Document Databases with MongoDBMongoDB.local Sydney: An Introduction to Document Databases with MongoDB
MongoDB.local Sydney: An Introduction to Document Databases with MongoDB
 
how_can_businesses_address_storage_issues_using_mongodb.pdf
how_can_businesses_address_storage_issues_using_mongodb.pdfhow_can_businesses_address_storage_issues_using_mongodb.pdf
how_can_businesses_address_storage_issues_using_mongodb.pdf
 
SQL vs NoSQL, an experiment with MongoDB
SQL vs NoSQL, an experiment with MongoDBSQL vs NoSQL, an experiment with MongoDB
SQL vs NoSQL, an experiment with MongoDB
 
Copy of MongoDB .pptx
Copy of MongoDB .pptxCopy of MongoDB .pptx
Copy of MongoDB .pptx
 
how_can_businesses_address_storage_issues_using_mongodb.pptx
how_can_businesses_address_storage_issues_using_mongodb.pptxhow_can_businesses_address_storage_issues_using_mongodb.pptx
how_can_businesses_address_storage_issues_using_mongodb.pptx
 
Accra MongoDB User Group
Accra MongoDB User GroupAccra MongoDB User Group
Accra MongoDB User Group
 
MongoDB NoSQL - Developer Guide
MongoDB NoSQL - Developer GuideMongoDB NoSQL - Developer Guide
MongoDB NoSQL - Developer Guide
 
Mongo db halloween party
Mongo db halloween partyMongo db halloween party
Mongo db halloween party
 
MongoDB
MongoDBMongoDB
MongoDB
 
Mongo db dhruba
Mongo db dhrubaMongo db dhruba
Mongo db dhruba
 
Mongo db transcript
Mongo db transcriptMongo db transcript
Mongo db transcript
 
Mongodb By Vipin
Mongodb By VipinMongodb By Vipin
Mongodb By Vipin
 
Big Data, NoSQL with MongoDB and Cassasdra
Big Data, NoSQL with MongoDB and CassasdraBig Data, NoSQL with MongoDB and Cassasdra
Big Data, NoSQL with MongoDB and Cassasdra
 
Jumpstart: Building Your First MongoDB App
Jumpstart: Building Your First MongoDB AppJumpstart: Building Your First MongoDB App
Jumpstart: Building Your First MongoDB App
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentation
 

Dernier

UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 

Dernier (20)

UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 

Mongo db basics

  • 1. MongoDB - Basics Apr - 2013 cm@paybook.com Friday, May 24, 13
  • 2. Overview MongoDB is a document database that provides high performance, high availability, and easy scalability. • Document Database ◦ Documents (objects) map nicely to programming language data types. ◦ Embedded documents and arrays reduce need for joins. ◦ Dynamic schema makes polymorphism easier. • High Performance ◦ Embedding makes reads and writes fast. ◦ Indexes can include keys from embedded documents and arrays. ◦ Optional streaming writes (no acknowledgments). • High Availability ◦ Replicated servers with automatic master failover. • Easy Scalability ◦ Automatic sharding distributes collection data across machines. ◦ Eventually-consistent reads can be distributed over replicated servers Friday, May 24, 13
  • 3. A MongoDB deployment hosts a number of databases.A database holds a set of collections.A collection holds a set of documents.A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data. Mongo Data Model Databases Collections Documents Host Friday, May 24, 13
  • 4. Queries Like others databases engines MongoDB supports different kind of queries. • Find • Insert • Update • Delete Friday, May 24, 13
  • 5. Deployment MongoDB has the installing capability with the following configuration. • Standalone (Single-instance). • Replica sets, high performance replication with automated failover. • Shared clusters, partition large data sets over many machines, transparently to the users (horizontal scalability) Friday, May 24, 13
  • 6. Technical Facts • MongoDB is a server process that runs on Linux,Windows and OS X. It can be run both as a 32 or 64-bit application.We recommend running in 64-bit mode, since MongoDB is limited to a total data size of about 2GB for all databases in 32-bit mode. • The MongoDB process listens on port 27017 by default. • Clients connect to the MongoDB process, optionally authenticate themselves if security is turned on. • MongoDB stores its data in files (default location is /data/db/), and uses memory mapped files for data management for efficiency. Friday, May 24, 13
  • 7. NoSQL A NoSQL database provides a mechanism for storage and retrieval of data that use looser consistency models than traditional relational databases in order to achieve horizontal scaling and higher availability. • Features. • Dynamic Schemas (Schemaless). • Auto-replication and sharding. • Integrated cache • Speed Friday, May 24, 13
  • 9. Key–value stores allow the application to store its data in a schema- less way.The data could be stored in a datatype of a programming language or an object. Because of this, there is no need for a fixed data model. A schemaless database allows any data, structured with individual fields and structures, to be stored in the database. Being schemaless reduces ceremony (you don't have to define schemas) and increases flexibility (you can store all sorts of data without prior definition). Schema-less Friday, May 24, 13
  • 10. Pros • The data structures that you design on your programming language are mapped into the database. • ALTER TABLE commands are no longer required. Cons • Not designing the data model schema at the first stage can lead to weak or inconsistent data model in later stage of the application. • You may eventually duplicate the schema across applications. Schema-less Friday, May 24, 13
  • 11. JavaScript • JavaScript (JS) is an interpreted computer programming language. It was originally implemented as part of web browsers so that client-side scripts could interact with the user, control the browser, communicate asynchronously, and alter the document content that was displayed. • JavaScript's use in applications outside of web pages—for example, in PDF documents, site-specific browsers, and desktop widgets—is also significant. Newer and faster JavaScriptVMs and frameworks built upon them (notably Node.js) have also increased the popularity of JavaScript for server-side web applications. Friday, May 24, 13
  • 12. JavaScript & MongoDB • In earlier versions was based on SpiderMonkey engine. • No in 2.4 version MongoDB is based on a JavaScript engine calledV8. • Improved concurrency for JavaScript operations, • Modernized JavaScript implementation, and • Removed non-standard SpiderMonkey features Friday, May 24, 13
  • 13. JSON • JavaScript Object Notation • Is a lightweight data-interchange format. • It is easy for humans to read and write. • It is easy for machines to parse and generate. • Is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages. Friday, May 24, 13
  • 14. JSON JSON is built on two structures: • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. Friday, May 24, 13
  • 17. BSON A serialization format used to store documents and make remote procedure calls in MongoDB.“BSON” is a portmanteau of the words “binary” and “JSON”.Think of BSON as a binary representation of JSON (JavaScript Object Notation) documents. For a detailed spec, see bsonspec.org. Friday, May 24, 13
  • 18. BSON Data types Type Type Double Regular expression String JavaScript Object Symbol Array 32-bit integer Binary data Timestamp Object ID 64-bit integer Boolean Min key Date Max key Null Friday, May 24, 13
  • 19. Drivers • Are available for the following languages. C Node.js* C++ Perl C# PHP Erlang Python Java Ruby JavaScript Scala * Node.js based on JavaScript Friday, May 24, 13
  • 21. Installing MongoDB • Windows - http://docs.mongodb.org/manual/ tutorial/install-mongodb-on-windows/ • Mac - http://docs.mongodb.org/manual/ tutorial/install-mongodb-on-os-x/ • Linux - http://docs.mongodb.org/manual/ tutorial/install-mongodb-on-linux/ Friday, May 24, 13
  • 22. Mongo Shell The mongo shell is an interactive JavaScript shell for MongoDB, and is part of all MongoDB distributions. Friday, May 24, 13
  • 23. Workshop 1. Debian linux virtual machine installed on virtualbox environment. 2. Start the virtual machine 3.The data access to the virtual machine is user: root password: mongodb2013 Friday, May 24, 13
  • 24. Mongo shell data types MongoDB BSON provide support for additional data types than JSON. Drivers provide native support for these data types in host languages and the mongo shell also provides several helper classes to support the use of these data types in the mongo JavaScript shell. See MongoDB Extended JSON for additional information. • Date • ObjectId • NumberLong Friday, May 24, 13
  • 25. • To access to Mongo shell just type “mongo”. Mongo shell Friday, May 24, 13
  • 26. Mongo shell • To access to Mongo on other host shell just type “mongo host/database”. Friday, May 24, 13
  • 28. CRUD In computer programming, create, read, update and delete (CRUD) are the four basic functions of persistent storage. Sometimes CRUD is expanded with the words retrieve instead of read, modify instead of update, or destroy instead of delete. It is also sometimes used to describe user interface conventions that facilitate viewing, searching, and changing information; often using computer-based forms and reports. The acronym CRUD refers to all of the major functions that are implemented in relational database applications. Each letter in the acronym can map to a standard SQL statement and HTTP method: Making full use of HTTP methods, along with other constraints, is considered "RESTful". Friday, May 24, 13
  • 29. Mongo CRUD Operations • Create • Are those that add new records or documents to a collection in MongoDB. • insert() • update() • Read • Are those that retrieve records or documents from a collection in MongoDB • find() • findOne() Friday, May 24, 13
  • 30. Mongo CRUD Operations • Update • Are those that modify existing records or documents in a MongoDB collection • update() • Delete • Are those that remove documents from a collection in MongoDB • remove() Friday, May 24, 13
  • 31. Create The insert() method inserts a document or documents into a collection. Consider the following behaviors of the insert() method: • If the collection does not exist, then the insert() method will create the collection. • If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. • If the document specifies a new field, then the insert() method inserts the document with the new field. Friday, May 24, 13
  • 32. Create The insert() method takes one of the following parameters: • document – A document to insert into the collection. db.products.insert( { item: "card", qty: 15 } ) This operation inserts a new document into the products collection with the item field set to card, the qty field set to 15, and the _id field set to a unique ObjectId: { "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "card", "qty" : 15 } Friday, May 24, 13
  • 33. Create To insert a single document, with a custom _id field, include the _id field set to a unique identifier and pass the document to the insert() method as follows: db.products.insert( { _id: 10, item: "box", qty: 20 } ) This operation inserts a new document in the products collection with the _id field set to 10, the item field set to box, the qty field set to 20: { "_id" : 10, "item" : "box", "qty" : 20 } Friday, May 24, 13
  • 34. Create To insert multiple documents, pass an array of documents to the insert() method as in the following: db.products.insert( [ { _id: 11, item: "pencil", qty: 50, type: "no.2" }, { item: "pen", qty: 20 }, { item: "eraser", qty: 25 } ] ) Friday, May 24, 13
  • 35. Create The operation will insert three documents into the products collection: • A document with the fields _id set to 11, item set to pencil, qty set to 50, and the type set to no.2. • A document with the fields _id set to a unique objectid, item set to pen, and qty set to 20. • A document with the fields _id set to a unique objectid, item set to eraser, and qty set to 25. Friday, May 24, 13
  • 36. Create { "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" } { "_id" : ObjectId("50631bc0be4617f17bb159ca"), "item" : "pen", "qty" : 20 } { "_id" : ObjectId("50631bc0be4617f17bb159cb"), "item" : "eraser", "qty" : 25 } Friday, May 24, 13
  • 37. Exercise 1. Use the enoan database 2. Execute the following commands. - db.products.insert({item:"card", qty:15}); - db.products.insert({_id:10, item:"box", qty:20}); - db.products.insert([{ _id:11, item:"pencil", qty:50, type:"no. 2"},{item:"pen", qty:20},{item:"eraser", qty:25}]); Friday, May 24, 13
  • 38. Read The command to read data in a collection is find(query,projection). The syntax to use this command is db.collection.find() When the collection has a lot of documents the find automatically split the result in packages of 20 documents. Friday, May 24, 13
  • 39. Read Sometimes we need to count the number of documents on a collection with or without query filter. db.collection.find().count() Friday, May 24, 13
  • 41. Read Find one document db.collection.findOne() Format the result db.collection.find().pretty() Friday, May 24, 13
  • 42. Exercise 1. In the enoan database find all the documents on the zips collection. 1.1 Connect to enoan database using mongo shell 1.2 Execute: db.zips.find() Friday, May 24, 13
  • 44. Read The command find has the capability of query documents with a condition. Also has the option to project the results of some keys. The method takes the following parameters. query. Optional. Specifies the selection criteria using query operators. Omit the query parameter or pass an empty document (e.g. {}) to return all documents in the collection. projection. Optional. Controls the fields to return, or the projection.The _id key is always returned you must to ignore this key to hidde it. Friday, May 24, 13
  • 45. Read Some samples with zips collection. db.zips.find() Return all the information on the collection. db.zips.find({"state":"TX"}) Return all the documents where the state is equal to TX (Texas) db.zips.find({"state":"TX"},{"city":1,"state":1}) Return all the documents where the state is equal to TX (Texas) Shows only state and city keys Friday, May 24, 13
  • 46. Read Also we can use selection criteria in our queries. $gt. Greater than operator $gte. Greater than or equal operator $lt. Lower than operator $lte. Lower than or equal operator db.zips.find({"pop":{$gt:100000}}) Return all the documents where the pop key is greater than 100,000 db.zips.find({"pop":{$lt:5}}) Friday, May 24, 13
  • 47. Update The update() method modifies an existing document or documents in a collection. By default the update() method updates a single document.To update all documents in the collection that match the update query criteria, specify the multi option.To insert a document if no document matches the update query criteria, specify the upsert option. Friday, May 24, 13
  • 48. Update The update() method takes the following parameters: • query (document). Specifies the selection criteria for the update.The query parameter employs the same query selectors as used in the db.collection.find() method. • update (document). Specifies the modifications to apply. • upsert (boolean). Optional. Specifies an upsert operation • multi (boolean). Optional. Specifies whether to update multiple documents that meet the query criteria. Friday, May 24, 13
  • 49. Update Some notes about the upsert • The default value is false.When true, the update() method will update an existing document that matches the query selection criteria or if no document matches the criteria, insert a new document with the fields and values of the update parameter and if the update included only update operators, the query parameter as well. Some notes about the multi • When not specified, the default value is false and the update() method updates a single document that meet the query criteria. • When true, the update() method updates all documents that meet the query criteria. Friday, May 24, 13
  • 50. Update update() field operators $inc. increments a value of a field by a specified amount. If the field does not exist, $inc sets the field to the specified amount. $inc accepts positive and negative incremental amounts. db.collection.update( { field: value },{ $inc: { field1: amount } } ); db.collection.update( { age: 20 }, { $inc: { age: 1 } }); Friday, May 24, 13
  • 51. Update update() field operators $rename. updates the name of a field.The new field name must differ from the existing field name. {$rename: { <old name1>: <new name1>, <old name2>: <new name2>, ... } } db.students.update( { _id: 1 }, { $rename: { 'nickname': 'alias', 'cell': 'mobile' } } ) Friday, May 24, 13
  • 52. Update update() field operators $set. set a particular value db.collection.update( { field: value1 }, { $set: { field1: value2 } } ); This statement updates in the document in collection where field matches value1 by replacing the value of the field field1 with value2.This operator will add the specified field or fields if they do not exist in this document or replace the existing value of the specified field(s) if they already exist. Friday, May 24, 13
  • 53. Update update() field operators $unset. deletes a particular field db.collection.update( { field: value1 }, { $unset: { field1: "" } } ); The above example deletes field1 in collection from documents where field has a value of value1.The value of the field in the $unset statement (i.e. "" above) does not impact the operation. If documents match the initial query (e.g. { field: value1 } above) but do not have the field specified in the $unset operation (e.g. field1), then the statement has no effect on the document. Friday, May 24, 13
  • 54. Exercise 1. Update the product collection add 20 to qty only on the item named card. 2. Update the product collection change the name of the item box to boxes. 3. Update all the documents on the product collection add the key status with value 1. 4. Update all the documents on the product collection change the key qty to quantity. Friday, May 24, 13
  • 55. Remove The remove method removes documents from a collection. The remove() method can take the following parameters: • query (document) – Optional. Specifies the deletion criteria using query operators. Omit the query parameter or pass an empty document (e.g. {} ) to delete all documents in the collection. • justOne (boolean) – Optional.A boolean that limits the deletion to just one document.The default value is false. Set to true to delete only the first result. Friday, May 24, 13
  • 56. Remove Consider the following examples of the remove method.The remove() method can take the following parameters: • To remove all documents in a collection, call the remove method with no parameters: db.products.remove() • To remove the documents that match a deletion criteria, call the remove method with the query criteria: db.products.remove( { qty: { $gt: 20 } } ) • To remove the first document that match a deletion criteria, call the remove method with the query criteria and the justOne parameter set to true or 1: db.products.remove( { qty: { $gt: 20 } }, true ) Friday, May 24, 13
  • 57. Exercise 1. Remove the item on the product collection where _id is equal to 10. 2. Remove all the items on the zips collection where the pop are lower than or equal 1. Friday, May 24, 13
  • 60. Security Strategies for Reducing Risk The most effective way to reduce risk for MongoDB deployments is to run your entire MongoDB deployment, including all MongoDB components (i.e. mongod, mongos and application instances) in a trusted environment.Trusted environments use the following strategies to control access: • Network filter (e.g. firewall) rules that block all connections from unknown systems to MongoDB components. • Bind mongod and mongos instances to specific IP addresses to limit accessibility. • Limit MongoDB programs to non-public local networks, and virtual private networks. Friday, May 24, 13
  • 61. Security Strategies for Reducing Risk You may further reduce risk by: • Requiring authentication for access to MongoDB instances. • Requiring strong, complex, single purpose authentication credentials.This should be part of your internal security policy but is not currently configurable in MongoDB. • Deploying a model of least privilege, where all users have only the amount of access they need to accomplish required tasks, and no more. • Following the best application development and deployment practices, which includes: validating all inputs, managing sessions, and application-level access control. Friday, May 24, 13
  • 62. Replication Database replication ensures redundancy, backup, and automatic failover. Replication occurs through groups of servers known as replica sets. A MongoDB replica set is a cluster of mongod instances that replicate amongst one another and ensure automated failover. Most replica sets consist of two or more mongod instances with at most one of these designated as the primary and the rest as secondary members. Clients direct all writes to the primary, while the secondary members replicate from the primary asynchronously. Friday, May 24, 13
  • 64. Sharding Sharding distributes a single logical database system across a cluster of machines. Sharding is MongoDB’s approach to scaling out. Sharding partitions a collection and stores the different portions on different machines.When a database’s collections become too large for existing storage, you need only add a new machine. Sharding automatically distributes collection data to the new server. Sharding automatically balances data and load across machines. Sharding provides additional write capacity by distributing the write load over a number of mongod instances. Sharding allows users to increase the potential amount of data in the working set. Friday, May 24, 13
  • 66. References • Mongodb http://mongodb.org/ • 10gen http://10gen.com • JSON http://json.org • BSON http://bsonspec.org/ • Mongo DB Drivers http://docs.mongodb.org/ecosystem/drivers/ • PHP mongodb driver https://github.com/mongodb/mongo-php-driver • Python mongodb (Pymongo) driver http://api.mongodb.org/python/ current/installation.html Friday, May 24, 13