SlideShare a Scribd company logo
1 of 22
Download to read offline
© 2010, OpenThink Labs. All Rights Reserved
MongoDB
Creating, Updating and Deleting Document
Wildan Maulana
wildan.m@openthinklabs.com
© 2010, OpenThink Labs. All Rights Reserved
Overview
● Adding new documents to a collection
● Inserting and Saving Documents
– Batch Insert
– Inserts: Internals and Implications
● Removing documents from a collection
● Removing Documents
– Remove Speed
● Updating existing documents
● Document Replacement
● Using Modifiers
● Upserts
● Choosing the correct level of safety versus speed for all of these operations
● The Fastest Write This Side of Mississippi
© 2010, OpenThink Labs. All Rights Reserved
Inserting and Saving Documents
● Inserts are the basic method for adding data to
MongoDB. To insert a document into a collection,
use the collection’s insert method:
> db.foo.insert({"bar" : "baz"})
© 2010, OpenThink Labs. All Rights Reserved
Batch Insert
● If you have a situation where you are inserting multiple documents into a
collection, you can make the insert faster by using batch inserts. Batch
inserts allow you to pass an array of documents to the database.
● A batch insert is a single TCP request, meaning that you do not incur the
overhead of doing hundreds of individual requests
● Batch inserts are intended to be used in applications, such as for
inserting a couple hundred sensor data points into an analytics collection
at once.
● They are useful only if you are inserting multiple documents into a single
collection
● Current versions of MongoDB do not accept messages longer than
16MB
© 2010, OpenThink Labs. All Rights Reserved
Inserts: Internals and Implications
● When you perform an insert, the driver you are
using converts the data structure into BSON,
which it then sends to the database
● The database understands BSON and checks for
an "_id" key and that the document’s size does
not exceed 4MB, but other than that, it doesn’t do
data validation; it just saves the document to the
database as is.
© 2010, OpenThink Labs. All Rights Reserved
Removing Documents
● Now that there’s data in our database, let’s delete
it.
● > db.users.remove()
● This will remove all of the documents in the users
collection. This doesn’t actually remove the collection,
and any indexes created on it will still exist.
● The remove function optionally takes a query document
as a parameter.
● > db.mailing.list.remove({"opt-out" :
true})
© 2010, OpenThink Labs. All Rights Reserved
Remove Speed
● Removing documents is usually a fairly quick operation, but if
you want to clear an entire collection, it is faster to drop it
(and then re-create any indexes).
for i in range(1000000):
collection.insert({"foo": "bar", "baz": i, "z": 10 - i})
import time
from pymongo import Connection
db = Connection().foo
collection = db.bar
start = time.time()
collection.remove()
collection.find_one()
total = time.time() - start
print "%d seconds" % total
46.08 s
import time
from pymongo import Connection
db = Connection().foo
collection = db.bar
start = time.time()
db.drop_collection("bar")
total = time.time() - start
print "%d seconds" % total
0.01 s
© 2010, OpenThink Labs. All Rights Reserved
Updating Documents
● Once a document is stored in the database, it can be changed using the
update method
● update takes two parameters: a query document, which locates
documents to update, and a modifier document, which describes the
changes to make to the documents found.
● Updates are atomic: if two updates happen at the same time, whichever
one reaches the server first will be applied, and then the next one will be
applied. Thus, conflicting
● updates can safely be sent in rapid-fire succession without any
documents being corrupted: the last update will “win.”
© 2010, OpenThink Labs. All Rights Reserved
Document Replacement
{
"_id" : ObjectId("4b2b9f67a1f631733d917a7a"),
"name" : "joe",
"friends" : 32,
"enemies" : 2
}
{
"_id" : ObjectId("4b2b9f67a1f631733d917a7a"),
"username" : "joe",
"relationships" :
{
"friends" : 32,
"enemies" : 2
}
}
We want to change that
document into the following:
© 2010, OpenThink Labs. All Rights Reserved
Document Replacement
> 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);
© 2010, OpenThink Labs. All Rights Reserved
Common Mistake
> db.people.find()
{"_id" : ObjectId("4b2b9f67a1f631733d917a7b"), "name" : "joe", "age" : 65},
{"_id" : ObjectId("4b2b9f67a1f631733d917a7c"), "name" : "joe", "age" : 20},
{"_id" : ObjectId("4b2b9f67a1f631733d917a7d"), "name" : "joe", "age" : 49},
> joe = db.people.findOne({"name" : "joe", "age" : 20});
{
"_id" : ObjectId("4b2b9f67a1f631733d917a7c"),
"name" : "joe",
"age" : 20
}
> joe.age++;
> db.people.update({"name" : "joe"}, joe);
E11001 duplicate key on update
© 2010, OpenThink Labs. All Rights Reserved
Using Modifiers
● Usually only certain portions of a document need
to be updated.
● Partial updates can be done extremely efficiently
by using atomic update modifiers
● Update modifiers are special keys that can be
used to specify complex update operations, such
as altering, adding, or removing keys, and even
manipulating arrays and embedded documents.
© 2010, OpenThink Labs. All Rights Reserved
Using Modifiers
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"url" : "www.example.com",
"pageviews" : 52
}
> db.analytics.update({"url" : "www.example.com"},
... {"$inc" : {"pageviews" : 1}})
use the "$inc"
modifier to increment the value of the "pageviews" key.
> db.analytics.find()
{
"_id" : ObjectId("4b253b067525f35f94b60a31"),
"url" : "www.example.com",
"pageviews" : 53
}
© 2010, OpenThink Labs. All Rights Reserved
Getting started with
the "$set" modifier
● "$set" sets the value of a key. If the key does not
yet exist, it will be created. This can be handy for
updating schema or adding user-defined keys
© 2010, OpenThink Labs. All Rights Reserved
> 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"
}
> db.users.update({"name" : "joe"},
... {"$set" : {"favorite book" : "green eggs and ham"}})
© 2010, OpenThink Labs. All Rights Reserved
Getting started with
the "$set" modifier
● "$set" can even change the type of the key it
modifies. For instance, if our fickle user decides
that he actually likes quite a few books, he can
change the value of the “favorite book” key into an
array:
> db.users.update({"name" : "joe"},
... {"$set" : {"favorite book" :
... ["cat's cradle", "foundation trilogy", "ender's game"]}})
> db.users.update({"name" : "joe"},
... {"$unset" : {"favorite book" : 1}})
remove the key altogether
with "$unset"
© 2010, OpenThink Labs. All Rights Reserved
Getting started with
the "$set" modifier
● You can also use "$set" to reach in and change
embedded documents:
> 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"
}
}
© 2010, OpenThink Labs. All Rights Reserved
Incrementing and decrementing
● 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. It is very
useful for updating analytics, karma, votes, or anything else that
has a changeable, numeric value.
> 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
}
© 2010, OpenThink Labs. All Rights Reserved
Incrementing and decrementing
> db.games.update({"game" : "pinball", "user" : "joe"},
... {"$inc" : {"score" : 10000}})
> db.games.find()
{
"_id" : ObjectId("4b2d75476cc613d5ee930164"),
"game" : "pinball",
"name" : "joe",
"score" : 10050
}
"$inc" is similar to "$set", but it is designed for incrementing (and decrementing)
numbers. "$inc" can be used only on values of type integer, long, or double. If it is used
on any other type of value, it will fail.
© 2010, OpenThink Labs. All Rights Reserved
To be continued … ^_^
© 2010, OpenThink Labs. All Rights Reserved
Buy this book, on Amazon!
© 2010, OpenThink Labs. All Rights Reserved
Q&A
Thanks! ^_^

More Related Content

What's hot

MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...MongoDB
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDBMongoDB
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningMongoDB
 
Building a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and JavaBuilding a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and Javaantoinegirbal
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introductionantoinegirbal
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDBantoinegirbal
 
Indexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleIndexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleMongoDB
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)MongoDB
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationMongoDB
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDBNate Abele
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBMongoDB
 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDBJames Williams
 
5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDB5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDBTim Callaghan
 
Superficial mongo db
Superficial mongo dbSuperficial mongo db
Superficial mongo dbDaeMyung Kang
 

What's hot (19)

MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
 
Indexing with MongoDB
Indexing with MongoDBIndexing with MongoDB
Indexing with MongoDB
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
Building a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and JavaBuilding a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and Java
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
 
Indexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleIndexing Strategies to Help You Scale
Indexing Strategies to Help You Scale
 
Mongo db queries
Mongo db queriesMongo db queries
Mongo db queries
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB Application
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDB
 
5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDB5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDB
 
Superficial mongo db
Superficial mongo dbSuperficial mongo db
Superficial mongo db
 

Viewers also liked (7)

Data file handling
Data file handlingData file handling
Data file handling
 
Chap 1 c++
Chap 1 c++Chap 1 c++
Chap 1 c++
 
Filehandling
FilehandlingFilehandling
Filehandling
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
file handling c++
file handling c++file handling c++
file handling c++
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 

Similar to Creating, Updating and Deleting Document in MongoDB

Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBMongoDB
 
Back to Basics Webinar 2 - Your First MongoDB Application
Back to  Basics Webinar 2 - Your First MongoDB ApplicationBack to  Basics Webinar 2 - Your First MongoDB Application
Back to Basics Webinar 2 - Your First MongoDB ApplicationJoe Drumgoole
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBBack to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBMongoDB
 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)Uwe Printz
 
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...MongoDB
 
Back to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB ApplicationBack to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB ApplicationJoe Drumgoole
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesDoris Chen
 
Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDBNorberto Leite
 
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...MongoDB
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBMongoDB
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlTO THE NEW | Technology
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverMongoDB
 
MongoDB Schema Design: Practical Applications and Implications
MongoDB Schema Design: Practical Applications and ImplicationsMongoDB Schema Design: Practical Applications and Implications
MongoDB Schema Design: Practical Applications and ImplicationsMongoDB
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesDoris Chen
 
Eagle6 mongo dc revised
Eagle6 mongo dc revisedEagle6 mongo dc revised
Eagle6 mongo dc revisedMongoDB
 

Similar to Creating, Updating and Deleting Document in MongoDB (20)

Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Back to Basics Webinar 2 - Your First MongoDB Application
Back to  Basics Webinar 2 - Your First MongoDB ApplicationBack to  Basics Webinar 2 - Your First MongoDB Application
Back to Basics Webinar 2 - Your First MongoDB Application
 
The emerging world of mongo db csp
The emerging world of mongo db   cspThe emerging world of mongo db   csp
The emerging world of mongo db csp
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBBack to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDB
 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)
 
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
 
Back to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB ApplicationBack to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB Application
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
 
Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDB
 
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
 
Latinoware
LatinowareLatinoware
Latinoware
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behl
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET Driver
 
MongoDB Schema Design: Practical Applications and Implications
MongoDB Schema Design: Practical Applications and ImplicationsMongoDB Schema Design: Practical Applications and Implications
MongoDB Schema Design: Practical Applications and Implications
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Eagle6 mongo dc revised
Eagle6 mongo dc revisedEagle6 mongo dc revised
Eagle6 mongo dc revised
 

More from Wildan Maulana

Hasil Pendataan Potensi Desa 2018
Hasil Pendataan Potensi Desa 2018Hasil Pendataan Potensi Desa 2018
Hasil Pendataan Potensi Desa 2018Wildan Maulana
 
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...Wildan Maulana
 
Ketahanan Pangan #1 : Gerakan Sekolah Menanam Melon
Ketahanan Pangan #1 : Gerakan Sekolah Menanam MelonKetahanan Pangan #1 : Gerakan Sekolah Menanam Melon
Ketahanan Pangan #1 : Gerakan Sekolah Menanam MelonWildan Maulana
 
Pengembangan OpenThink SAS 2013-2014
Pengembangan OpenThink SAS 2013-2014Pengembangan OpenThink SAS 2013-2014
Pengembangan OpenThink SAS 2013-2014Wildan Maulana
 
ICA – AtoM : Retensi Arsip
ICA – AtoM : Retensi ArsipICA – AtoM : Retensi Arsip
ICA – AtoM : Retensi ArsipWildan Maulana
 
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RW
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RWOpenThink Labs Workshop : Ketahanan Pangan Skala RT/RW
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RWWildan Maulana
 
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...Wildan Maulana
 
PostgreSQL BootCamp : Manajemen Master Data dengan SkyTools
PostgreSQL BootCamp : Manajemen Master Data dengan SkyToolsPostgreSQL BootCamp : Manajemen Master Data dengan SkyTools
PostgreSQL BootCamp : Manajemen Master Data dengan SkyToolsWildan Maulana
 
Mensetup Google Apps sebagai IdP jenis openID dan Aplikasi Berbasis CakePHP ...
Mensetup Google Apps sebagai IdP jenis openID  dan Aplikasi Berbasis CakePHP ...Mensetup Google Apps sebagai IdP jenis openID  dan Aplikasi Berbasis CakePHP ...
Mensetup Google Apps sebagai IdP jenis openID dan Aplikasi Berbasis CakePHP ...Wildan Maulana
 
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai Sp
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai SpMensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai Sp
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai SpWildan Maulana
 
Konfigurasi simpleSAMLphp dengan Google Apps Sebagai Identity Provider
Konfigurasi simpleSAMLphp  dengan Google Apps Sebagai Identity ProviderKonfigurasi simpleSAMLphp  dengan Google Apps Sebagai Identity Provider
Konfigurasi simpleSAMLphp dengan Google Apps Sebagai Identity ProviderWildan Maulana
 
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)Instalasi simpleSAMLphp sebagai Identity Provider (IdP)
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)Wildan Maulana
 
Instalasi dan Konfigurasi simpleSAMLphp
Instalasi dan Konfigurasi simpleSAMLphpInstalasi dan Konfigurasi simpleSAMLphp
Instalasi dan Konfigurasi simpleSAMLphpWildan Maulana
 
River Restoration in Asia and Connection Between IWRM and River Restoration
River Restoration in Asia and Connection Between IWRM and River RestorationRiver Restoration in Asia and Connection Between IWRM and River Restoration
River Restoration in Asia and Connection Between IWRM and River RestorationWildan Maulana
 
Optimasi Limpasan Air Limbah Ke Kali Surabaya (Segmen Sepanjang – Jagir) De...
Optimasi Limpasan Air Limbah  Ke Kali Surabaya (Segmen Sepanjang – Jagir)  De...Optimasi Limpasan Air Limbah  Ke Kali Surabaya (Segmen Sepanjang – Jagir)  De...
Optimasi Limpasan Air Limbah Ke Kali Surabaya (Segmen Sepanjang – Jagir) De...Wildan Maulana
 
Penilaian Siswa di Finlandia - Pendidikan Dasar
Penilaian Siswa di Finlandia - Pendidikan DasarPenilaian Siswa di Finlandia - Pendidikan Dasar
Penilaian Siswa di Finlandia - Pendidikan DasarWildan Maulana
 
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and Uses
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and UsesProyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and Uses
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and UsesWildan Maulana
 
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang Tua
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang TuaOpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang Tua
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang TuaWildan Maulana
 
Menggunakan AlisJK : Equating
Menggunakan AlisJK : EquatingMenggunakan AlisJK : Equating
Menggunakan AlisJK : EquatingWildan Maulana
 

More from Wildan Maulana (20)

Hasil Pendataan Potensi Desa 2018
Hasil Pendataan Potensi Desa 2018Hasil Pendataan Potensi Desa 2018
Hasil Pendataan Potensi Desa 2018
 
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...
Double for Nothing? Experimental Evidence on an Unconditional TeacherSalary I...
 
Ketahanan Pangan #1 : Gerakan Sekolah Menanam Melon
Ketahanan Pangan #1 : Gerakan Sekolah Menanam MelonKetahanan Pangan #1 : Gerakan Sekolah Menanam Melon
Ketahanan Pangan #1 : Gerakan Sekolah Menanam Melon
 
Pengembangan OpenThink SAS 2013-2014
Pengembangan OpenThink SAS 2013-2014Pengembangan OpenThink SAS 2013-2014
Pengembangan OpenThink SAS 2013-2014
 
ICA – AtoM : Retensi Arsip
ICA – AtoM : Retensi ArsipICA – AtoM : Retensi Arsip
ICA – AtoM : Retensi Arsip
 
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RW
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RWOpenThink Labs Workshop : Ketahanan Pangan Skala RT/RW
OpenThink Labs Workshop : Ketahanan Pangan Skala RT/RW
 
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...
OpenThink Labs : Dengar Pendapat Komunitas ciliwung dengan kemen pu dan kemen...
 
PostgreSQL BootCamp : Manajemen Master Data dengan SkyTools
PostgreSQL BootCamp : Manajemen Master Data dengan SkyToolsPostgreSQL BootCamp : Manajemen Master Data dengan SkyTools
PostgreSQL BootCamp : Manajemen Master Data dengan SkyTools
 
Mensetup Google Apps sebagai IdP jenis openID dan Aplikasi Berbasis CakePHP ...
Mensetup Google Apps sebagai IdP jenis openID  dan Aplikasi Berbasis CakePHP ...Mensetup Google Apps sebagai IdP jenis openID  dan Aplikasi Berbasis CakePHP ...
Mensetup Google Apps sebagai IdP jenis openID dan Aplikasi Berbasis CakePHP ...
 
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai Sp
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai SpMensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai Sp
Mensetup Google Apps sebagai IdP jenis openID dan Wordpress sebagai Sp
 
Konfigurasi simpleSAMLphp dengan Google Apps Sebagai Identity Provider
Konfigurasi simpleSAMLphp  dengan Google Apps Sebagai Identity ProviderKonfigurasi simpleSAMLphp  dengan Google Apps Sebagai Identity Provider
Konfigurasi simpleSAMLphp dengan Google Apps Sebagai Identity Provider
 
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)Instalasi simpleSAMLphp sebagai Identity Provider (IdP)
Instalasi simpleSAMLphp sebagai Identity Provider (IdP)
 
Instalasi dan Konfigurasi simpleSAMLphp
Instalasi dan Konfigurasi simpleSAMLphpInstalasi dan Konfigurasi simpleSAMLphp
Instalasi dan Konfigurasi simpleSAMLphp
 
River Restoration in Asia and Connection Between IWRM and River Restoration
River Restoration in Asia and Connection Between IWRM and River RestorationRiver Restoration in Asia and Connection Between IWRM and River Restoration
River Restoration in Asia and Connection Between IWRM and River Restoration
 
Optimasi Limpasan Air Limbah Ke Kali Surabaya (Segmen Sepanjang – Jagir) De...
Optimasi Limpasan Air Limbah  Ke Kali Surabaya (Segmen Sepanjang – Jagir)  De...Optimasi Limpasan Air Limbah  Ke Kali Surabaya (Segmen Sepanjang – Jagir)  De...
Optimasi Limpasan Air Limbah Ke Kali Surabaya (Segmen Sepanjang – Jagir) De...
 
Penilaian Siswa di Finlandia - Pendidikan Dasar
Penilaian Siswa di Finlandia - Pendidikan DasarPenilaian Siswa di Finlandia - Pendidikan Dasar
Penilaian Siswa di Finlandia - Pendidikan Dasar
 
Statistik Listrik
Statistik ListrikStatistik Listrik
Statistik Listrik
 
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and Uses
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and UsesProyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and Uses
Proyek Al-'Alaq : Electric Bicycles ; History, Characteristics, and Uses
 
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang Tua
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang TuaOpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang Tua
OpenThink SAS : Interaksi Antara Sekolah, Wali Kelas, Siswa dan Orang Tua
 
Menggunakan AlisJK : Equating
Menggunakan AlisJK : EquatingMenggunakan AlisJK : Equating
Menggunakan AlisJK : Equating
 

Recently uploaded

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Recently uploaded (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Creating, Updating and Deleting Document in MongoDB

  • 1. © 2010, OpenThink Labs. All Rights Reserved MongoDB Creating, Updating and Deleting Document Wildan Maulana wildan.m@openthinklabs.com
  • 2. © 2010, OpenThink Labs. All Rights Reserved Overview ● Adding new documents to a collection ● Inserting and Saving Documents – Batch Insert – Inserts: Internals and Implications ● Removing documents from a collection ● Removing Documents – Remove Speed ● Updating existing documents ● Document Replacement ● Using Modifiers ● Upserts ● Choosing the correct level of safety versus speed for all of these operations ● The Fastest Write This Side of Mississippi
  • 3. © 2010, OpenThink Labs. All Rights Reserved Inserting and Saving Documents ● Inserts are the basic method for adding data to MongoDB. To insert a document into a collection, use the collection’s insert method: > db.foo.insert({"bar" : "baz"})
  • 4. © 2010, OpenThink Labs. All Rights Reserved Batch Insert ● If you have a situation where you are inserting multiple documents into a collection, you can make the insert faster by using batch inserts. Batch inserts allow you to pass an array of documents to the database. ● A batch insert is a single TCP request, meaning that you do not incur the overhead of doing hundreds of individual requests ● Batch inserts are intended to be used in applications, such as for inserting a couple hundred sensor data points into an analytics collection at once. ● They are useful only if you are inserting multiple documents into a single collection ● Current versions of MongoDB do not accept messages longer than 16MB
  • 5. © 2010, OpenThink Labs. All Rights Reserved Inserts: Internals and Implications ● When you perform an insert, the driver you are using converts the data structure into BSON, which it then sends to the database ● The database understands BSON and checks for an "_id" key and that the document’s size does not exceed 4MB, but other than that, it doesn’t do data validation; it just saves the document to the database as is.
  • 6. © 2010, OpenThink Labs. All Rights Reserved Removing Documents ● Now that there’s data in our database, let’s delete it. ● > db.users.remove() ● This will remove all of the documents in the users collection. This doesn’t actually remove the collection, and any indexes created on it will still exist. ● The remove function optionally takes a query document as a parameter. ● > db.mailing.list.remove({"opt-out" : true})
  • 7. © 2010, OpenThink Labs. All Rights Reserved Remove Speed ● Removing documents is usually a fairly quick operation, but if you want to clear an entire collection, it is faster to drop it (and then re-create any indexes). for i in range(1000000): collection.insert({"foo": "bar", "baz": i, "z": 10 - i}) import time from pymongo import Connection db = Connection().foo collection = db.bar start = time.time() collection.remove() collection.find_one() total = time.time() - start print "%d seconds" % total 46.08 s import time from pymongo import Connection db = Connection().foo collection = db.bar start = time.time() db.drop_collection("bar") total = time.time() - start print "%d seconds" % total 0.01 s
  • 8. © 2010, OpenThink Labs. All Rights Reserved Updating Documents ● Once a document is stored in the database, it can be changed using the update method ● update takes two parameters: a query document, which locates documents to update, and a modifier document, which describes the changes to make to the documents found. ● Updates are atomic: if two updates happen at the same time, whichever one reaches the server first will be applied, and then the next one will be applied. Thus, conflicting ● updates can safely be sent in rapid-fire succession without any documents being corrupted: the last update will “win.”
  • 9. © 2010, OpenThink Labs. All Rights Reserved Document Replacement { "_id" : ObjectId("4b2b9f67a1f631733d917a7a"), "name" : "joe", "friends" : 32, "enemies" : 2 } { "_id" : ObjectId("4b2b9f67a1f631733d917a7a"), "username" : "joe", "relationships" : { "friends" : 32, "enemies" : 2 } } We want to change that document into the following:
  • 10. © 2010, OpenThink Labs. All Rights Reserved Document Replacement > 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);
  • 11. © 2010, OpenThink Labs. All Rights Reserved Common Mistake > db.people.find() {"_id" : ObjectId("4b2b9f67a1f631733d917a7b"), "name" : "joe", "age" : 65}, {"_id" : ObjectId("4b2b9f67a1f631733d917a7c"), "name" : "joe", "age" : 20}, {"_id" : ObjectId("4b2b9f67a1f631733d917a7d"), "name" : "joe", "age" : 49}, > joe = db.people.findOne({"name" : "joe", "age" : 20}); { "_id" : ObjectId("4b2b9f67a1f631733d917a7c"), "name" : "joe", "age" : 20 } > joe.age++; > db.people.update({"name" : "joe"}, joe); E11001 duplicate key on update
  • 12. © 2010, OpenThink Labs. All Rights Reserved Using Modifiers ● Usually only certain portions of a document need to be updated. ● Partial updates can be done extremely efficiently by using atomic update modifiers ● Update modifiers are special keys that can be used to specify complex update operations, such as altering, adding, or removing keys, and even manipulating arrays and embedded documents.
  • 13. © 2010, OpenThink Labs. All Rights Reserved Using Modifiers { "_id" : ObjectId("4b253b067525f35f94b60a31"), "url" : "www.example.com", "pageviews" : 52 } > db.analytics.update({"url" : "www.example.com"}, ... {"$inc" : {"pageviews" : 1}}) use the "$inc" modifier to increment the value of the "pageviews" key. > db.analytics.find() { "_id" : ObjectId("4b253b067525f35f94b60a31"), "url" : "www.example.com", "pageviews" : 53 }
  • 14. © 2010, OpenThink Labs. All Rights Reserved Getting started with the "$set" modifier ● "$set" sets the value of a key. If the key does not yet exist, it will be created. This can be handy for updating schema or adding user-defined keys
  • 15. © 2010, OpenThink Labs. All Rights Reserved > 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" } > db.users.update({"name" : "joe"}, ... {"$set" : {"favorite book" : "green eggs and ham"}})
  • 16. © 2010, OpenThink Labs. All Rights Reserved Getting started with the "$set" modifier ● "$set" can even change the type of the key it modifies. For instance, if our fickle user decides that he actually likes quite a few books, he can change the value of the “favorite book” key into an array: > db.users.update({"name" : "joe"}, ... {"$set" : {"favorite book" : ... ["cat's cradle", "foundation trilogy", "ender's game"]}}) > db.users.update({"name" : "joe"}, ... {"$unset" : {"favorite book" : 1}}) remove the key altogether with "$unset"
  • 17. © 2010, OpenThink Labs. All Rights Reserved Getting started with the "$set" modifier ● You can also use "$set" to reach in and change embedded documents: > 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" } }
  • 18. © 2010, OpenThink Labs. All Rights Reserved Incrementing and decrementing ● 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. It is very useful for updating analytics, karma, votes, or anything else that has a changeable, numeric value. > 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 }
  • 19. © 2010, OpenThink Labs. All Rights Reserved Incrementing and decrementing > db.games.update({"game" : "pinball", "user" : "joe"}, ... {"$inc" : {"score" : 10000}}) > db.games.find() { "_id" : ObjectId("4b2d75476cc613d5ee930164"), "game" : "pinball", "name" : "joe", "score" : 10050 } "$inc" is similar to "$set", but it is designed for incrementing (and decrementing) numbers. "$inc" can be used only on values of type integer, long, or double. If it is used on any other type of value, it will fail.
  • 20. © 2010, OpenThink Labs. All Rights Reserved To be continued … ^_^
  • 21. © 2010, OpenThink Labs. All Rights Reserved Buy this book, on Amazon!
  • 22. © 2010, OpenThink Labs. All Rights Reserved Q&A Thanks! ^_^