SlideShare a Scribd company logo
Using Change Streams to
Keep Up With Your Data
Kevin Albertson, Software Engineer II
Kevin Albertson
Software Engineer II, MongoDB

@kevinAlbs
Why Real-Time Data?
March 8th, 2018
March 8th, 2018
Point A
Point B
MongoDB World 2018: Using Change Streams to Keep Up with Your Data
MongoDB World 2018: Using Change Streams to Keep Up with Your Data
March 8th, 2018
6:33 6:45 6:54
Tw
eet:everything
ok
Iarrive
atstation
Train
scheduled
7:00
Stillw
aiting
7:15
Stillw
aiting
March 8th, 2018
6:33 6:45 6:54
Tw
eet:everything
ok
Iarrive
atstation
Train
scheduled
7:15
Stillw
aiting
7:00
Stillw
aiting
6:33 6:45 6:54
Tw
eet:everything
ok
Iarrive
atstation
Train
scheduled
7:30
Stillw
aiting
7:15
Stillw
aiting
7:00
Stillw
aiting
6:33 6:45 6:54
Tw
eet:everything
ok
Iarrive
atstation
Train
scheduled
7:30
Stillw
aiting
7:15
Stillw
aiting
7:00
Stillw
aiting
7:45
Stillw
aiting
March 8th, 2018
6:33 6:45 6:54
Tw
eet:everything
ok
Iarrive
atstation
Train
scheduled
8:00
A
nnouncem
ent
7:30
Stillw
aiting
7:15
Stillw
aiting
7:00
Stillw
aiting
7:45
Stillw
aiting
March 8th, 2018
Unnecessary
6:33 6:45 6:54
Tw
eet:everything
ok
Iarrive
atstation
Train
scheduled
8:00
A
nnouncem
ent
7:30
Stillw
aiting
7:15
Stillw
aiting
7:00
Train
passes
7:45
Stillw
aiting
Arrive
in
N
YC
9:30
Take
train
in
otherdirection
9:30
Take
train
to
N
YC 11:00
Real-time is an Expectation
Change Streams Enable Existing Apps to
Provide Real-time Data
const	changeStream	=	
db.collection('train').watch();	
c h a n g e S t r e a m . o n ( ' c h a n g e ' , 	 ( c h a n g e ) 	 = > 	 { 	 c o n s o l e . l o g 	 ( c h a n g e ) 	 } ) ;
Added in 3.6
Improved in 4.0
{
"_id" : (resumeToken),
"operationType" : "insert",
"ns" : { "db" : "test", "coll" : "train" },
"documentKey" : {
"_id" : 123
},
"fullDocument" : {
"_id" : 123,
"text": "hello"
},
}
Change Stream
Characteristics
1. Use Collection Access Controls
2. Present a Defined API
3. Scale Across Nodes
Change Streams
Return 5 Operation Types
1. Insert
2. Update
3. Replace
4. Delete
5. Invalidate
mongos
3 2
1
Shard	1 Shard	2 Shard	3
Total Ordering of Changes Across Shards
Documents Uniquely Identified
Shard key combined with _id to uniquely identify documents
mongos
Shard	2 Shard	3Shard	1
Changes are Durable
S
S
collection.watch()
P
Change Streams are Resumable
collection.watch()
PP
{	
	_id:	<resumeToken>,	
	operationType:	'update'	
	...	
}	


SP
S
Change Streams are Resumable
changeStream.on ('change', (change) => {
console.log(change);
cachedResumeToken = change["_id"];
});
changeStream.on ('error', () => {
if (cachedResumeToken) {
establishChangeStream (cachedResumeToken);
}
});
Change Streams Utilize the Power of the
Aggregation Framework
$match $project $addFields $replaceRoot $redact
var	changeStream	=	coll.watch([{	$match:	{operationType:	{$in:	['delete',	'replace']}}}]);
1. Collection Access Controls
2. Defined API
3. Enable Scaling
4. Total Ordering
5. Durable
6. Resumable
7. Power of Aggregation
Types of Changes
Insert
> db.collection.watch([],
{maxAwaitTimeMS: 30000}).pretty()
> db.collection.insert({
_id: 1,
text: "hello"
})
Shell 1 Shell 2
{
"_id" : (resumeToken),
"operationType" : "insert",
"ns" : {
"db" : "test",
"coll" : "test"
},
"documentKey" : {
"_id" : 1
},
"fullDocument" : {
"_id" : 1,
"text": "hello"
},
}
Update
> db.collection.watch([],
{maxAwaitTimeMS: 30000}).pretty()
> db.collection.updateOne({_id: 1},
{ $set: {“text”: “updated”} })
Shell 1 Shell 2
{
"_id" : (resumeToken),
"operationType" : "update",
"ns" : {
"db" : "test",
"coll" : "collection"
},
"documentKey" : {
"_id" : 1
},
"updateDescription" : {
"updatedFields" : {
"text" : "updated"
},
"removedFields" : [ ]
}
}
Update with fullDocument: updateLookup
> db.collection.watch([],
{ fullDocument: “updateLookup”,
maxAwaitTimeMS: 30000 }).pretty()
> db.collection.updateOne({_id: 1},
{ $set: {“number”: “5”} })
Shell 1 Shell 2
{ "_id" : (resumeToken),
"operationType" : "update",
"fullDocument" : {
"_id" : 1,
"text" : "updated",
"number" : 5
},
"ns": {"db": "test", "coll": "collection"},
"documentKey" : { "_id" : 1 },
"updateDescription" : {
"updatedFields" : { "number" : 5 },
"removedFields" : [ ]
}
}
Replace
> db.collection.watch([],
{maxAwaitTimeMS: 30000}).pretty()
> db.collection.replaceOne({_id: 1},
{text: "replaced"})
Shell 1 Shell 2
{
"_id" : (resumeToken),
"operationType" : "replace",
"ns" : {
"db" : "test",
"coll" : "collection"
},
"documentKey" : {
"_id" : 1
},
"fullDocument" : {
"_id" : 1,
"text" : "replaced"
}
}
Delete
> db.collection.watch([],
{maxAwaitTimeMS: 30000}).pretty()
> db.collection.remove({_id: 1})
Shell 1 Shell 2
{
"_id" : (resumeToken),
"operationType" : "delete",
"ns" : {
"db" : "test",
"coll" : "collection"
},
"documentKey" : {
"_id" : 1
}
}
Invalidate
> db.collection.watch([],
{maxAwaitTimeMS: 30000}).pretty()
> db.collection.drop()
Shell 1 Shell 2
{
"_id" : (token),
"operationType" : "invalidate"
}
New in 4.0
1. startAtOperationTime
2. Change stream on db or client
3. Resumable before first change
Use Case
Real-time Train Arrival Estimates
Collection
> db.train.find().pretty()
{
"_id" : 11,
"position" : {
"lat" : 40.04714,
"lon" : -74.0351
}
}
App Caches State of All Trains
App Cache
_id: 11 (40.0, -74.0)
	db.train.find().readConcern("majority")
App Cache
Populate the Cache
_id: 11 (40.0, -74.0)
	db.train.watch([])
_id:	(resumeToken),	
operationType:	'update',	
updateDescription:	{	
		updatedFields:	{	lat:	40.41169	}	
},	
documentKey:	{_id:	11}	
Handled
_id:	(resumeToken),	
operationType:	'update',	
updateDescription:	{	
		updatedFields:	{	
					passengerCount:	5	
		}	
}	
documentKey:	{_id:	11}	
Handled?
App Cache _id: 11 (40.4, -74.0)
Watch for changes
$match to Filter Irrelevant Changes
db.train.watch([{	
				$match:	{	
								$or:	[	
												{'updateDescription.updatedFields.lat':	{$exists:	1}},	
												{'updateDescription.updatedFields.lon':	{$exists:	1}}	
								]	
				}	
}])
_id:	(resumeToken),	
operationType:	'insert',	
fullDocument:	{	
		_id:	16,	
		lat:	40.5889,	lon:	-76.1938	
},	
documentKey:	{_id:	16}
Ignored?
_id:	(resumeToken),	
operationType:	'update',	
updateDescription:	{	
		updatedFields:	{	
					passengerCount:	5	
		}	
}	
documentKey:	{_id:	11}
Ignored
App Cache _id: 11 (40.4, -74.0)
Handle All Document Changes
If Caching State of Documents:
db.train.watch([{	
				$match:	{	
								$or:	[	
												{	
																operationType:	'update',	
																$or:	[	
																				{'updateDescription.updatedFields.lat':	{$exists:	1}},	
																				{'updateDescription.updatedFields.lon':	{$exists:	1}}	
																]	
												},	
												{	operationType:	{	$in:	['delete',	'insert',	'replace']	}	}	
								]	
				}	
}])
App Cache _id: 11 (40.4, -74.0)
_id:	(resumeToken),	
operationType:	'insert',	
fullDocument:	{	
		_id:	16,	
		lat:	40.5889,	lon:	-76.1938	
},	
documentKey:	{_id:	16}
Handled
_id: 16 (40.4, -74.0)
_id:	(resumeToken),	
operationType:	'delete',	
documentKey:	{_id:	11}Handled
Race Between Populating and Listening!
	db.train.find().readConcern("majority")
.
.
.
	db.train.watch()
update occurs!
find
Client Server
[ {_id: 11}…], $clusterTime: X
watch, startAtOperationTime: X
start session
startAtOperationTime
startAtOperationTime
const session = client.startSession();
const cursor = db.collection('train').find({}, { session: session });
populateApplicationCache(cursor);
const changeStream = db.collection('train').watch([], {
session: session,
startAtOperationTime: session.operationTime
});
changeStream.on('change', updateApplicationCache);
App Complete!
1. Doesn't miss updates
2. Handles network blips
3. Reduces bandwidth
4. Easy to prototype
MongoDB World 2018: Using Change Streams to Keep Up with Your Data

More Related Content

PPTX
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
PPTX
MongoDB World 2018: Keynote
PDF
MongoDB World 2018: Building Intelligent Apps with MongoDB & Google Cloud
PDF
Map/Confused? A practical approach to Map/Reduce with MongoDB
PDF
Creating, Updating and Deleting Document in MongoDB
PDF
MongoDB World 2018: Overnight to 60 Seconds: An IOT ETL Performance Case Study
PPTX
Introduction to NOSQL And MongoDB
PDF
Building Apps with MongoDB
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
MongoDB World 2018: Keynote
MongoDB World 2018: Building Intelligent Apps with MongoDB & Google Cloud
Map/Confused? A practical approach to Map/Reduce with MongoDB
Creating, Updating and Deleting Document in MongoDB
MongoDB World 2018: Overnight to 60 Seconds: An IOT ETL Performance Case Study
Introduction to NOSQL And MongoDB
Building Apps with MongoDB

What's hot (19)

PPTX
Getting Started with MongoDB and NodeJS
PDF
Java development with MongoDB
PDF
MongoDB Performance Tuning
PPTX
Back to Basics Webinar 5: Introduction to the Aggregation Framework
DOC
Functions
PDF
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
KEY
The Principle of Hybrid App.
PPTX
Mythbusting: Understanding How We Measure the Performance of MongoDB
PPTX
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
PDF
Michael Hackstein - NoSQL meets Microservices - NoSQL matters Dublin 2015
PPT
Introduction to MongoDB
PDF
Elasticsearch at Dailymotion
PDF
MongoDB Europe 2016 - Debugging MongoDB Performance
PPTX
Back to Basics Webinar 3: Schema Design Thinking in Documents
PPTX
MongoDB - Back to Basics - La tua prima Applicazione
PPTX
Building a Scalable Inbox System with MongoDB and Java
PPTX
Morphia: Simplifying Persistence for Java and MongoDB
PDF
Building DSLs with Groovy
ODP
DrupalCon Chicago Practical MongoDB and Drupal
Getting Started with MongoDB and NodeJS
Java development with MongoDB
MongoDB Performance Tuning
Back to Basics Webinar 5: Introduction to the Aggregation Framework
Functions
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
The Principle of Hybrid App.
Mythbusting: Understanding How We Measure the Performance of MongoDB
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
Michael Hackstein - NoSQL meets Microservices - NoSQL matters Dublin 2015
Introduction to MongoDB
Elasticsearch at Dailymotion
MongoDB Europe 2016 - Debugging MongoDB Performance
Back to Basics Webinar 3: Schema Design Thinking in Documents
MongoDB - Back to Basics - La tua prima Applicazione
Building a Scalable Inbox System with MongoDB and Java
Morphia: Simplifying Persistence for Java and MongoDB
Building DSLs with Groovy
DrupalCon Chicago Practical MongoDB and Drupal
Ad

Similar to MongoDB World 2018: Using Change Streams to Keep Up with Your Data (20)

PPTX
MongoDB.local DC 2018: Scaling Realtime Apps with Change Streams
PPTX
Using Change Streams to Keep Up with Your Data
PPTX
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
PPTX
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
PPTX
Using Change Streams to Keep Up with Your Data
PPTX
Using Change Streams to Keep Up with Your Data
PDF
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
PPTX
[MongoDB.local Bengaluru 2018] Using Change Streams to Keep Up With Your Data
PDF
Getting Started with MongoDB: 4 Application Designs
PPTX
Using Change Streams to Keep Up with Your Data
PPTX
Insight on MongoDB Change Stream - Abhishek.D, Mydbops Team
PPTX
Neue Features in MongoDB 3.6
PPTX
What's new in MongoDB 3.6?
PDF
MongoDB World 2019: Scaling Real-time Collaboration with MongoDB
PDF
MongoDB for Coder Training (Coding Serbia 2013)
PPTX
Novedades de MongoDB 3.6
PPTX
MongoDB-SESSION03
PPTX
MongoDB.local Austin 2018: Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch A...
PDF
MongoDB World 2019: MongoDB Read Isolation: Making Your Reads Clean, Committe...
PDF
MongoDB World 2019: High Performance Auditing of Changes Based on MongoDB Cha...
MongoDB.local DC 2018: Scaling Realtime Apps with Change Streams
Using Change Streams to Keep Up with Your Data
MongoDB World 2018: Time for a Change Stream - Using MongoDB Change Streams t...
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
Using Change Streams to Keep Up with Your Data
Using Change Streams to Keep Up with Your Data
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
[MongoDB.local Bengaluru 2018] Using Change Streams to Keep Up With Your Data
Getting Started with MongoDB: 4 Application Designs
Using Change Streams to Keep Up with Your Data
Insight on MongoDB Change Stream - Abhishek.D, Mydbops Team
Neue Features in MongoDB 3.6
What's new in MongoDB 3.6?
MongoDB World 2019: Scaling Real-time Collaboration with MongoDB
MongoDB for Coder Training (Coding Serbia 2013)
Novedades de MongoDB 3.6
MongoDB-SESSION03
MongoDB.local Austin 2018: Ch-Ch-Ch-Ch-Changes: Taking Your MongoDB Stitch A...
MongoDB World 2019: MongoDB Read Isolation: Making Your Reads Clean, Committe...
MongoDB World 2019: High Performance Auditing of Changes Based on MongoDB Cha...
Ad

More from MongoDB (20)

PDF
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
PDF
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
PDF
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
PDF
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
PDF
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
PDF
MongoDB SoCal 2020: MongoDB Atlas Jump Start
PDF
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
PDF
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
PDF
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
PDF
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
PDF
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
PDF
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
PDF
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
PDF
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
PDF
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
PDF
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
PDF
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
PDF
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...

Recently uploaded (20)

PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Electronic commerce courselecture one. Pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
KodekX | Application Modernization Development
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Chapter 3 Spatial Domain Image Processing.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Electronic commerce courselecture one. Pdf
Building Integrated photovoltaic BIPV_UPV.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Spectral efficient network and resource selection model in 5G networks
Network Security Unit 5.pdf for BCA BBA.
NewMind AI Weekly Chronicles - August'25 Week I
Advanced methodologies resolving dimensionality complications for autism neur...
Programs and apps: productivity, graphics, security and other tools
KodekX | Application Modernization Development
Digital-Transformation-Roadmap-for-Companies.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Diabetes mellitus diagnosis method based random forest with bat algorithm
“AI and Expert System Decision Support & Business Intelligence Systems”
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

MongoDB World 2018: Using Change Streams to Keep Up with Your Data