<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Document Databases &#8211; Simon Jakowicz</title>
	<atom:link href="https://www.jakowicz.com/tag/document-databases/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.jakowicz.com</link>
	<description>Just another blogger</description>
	<lastBuildDate>
	Sat, 05 Dec 2026 18:20:01 +0000	</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.1.19</generator>
	<item>
		<title>MongoDB – Part 10 – Internals and Final Thoughts</title>
		<link>https://www.jakowicz.com/mongodb-part-10-tips-and-final-thoughts/</link>
				<comments>https://www.jakowicz.com/mongodb-part-10-tips-and-final-thoughts/#respond</comments>
				<pubDate>Mon, 28 Dec 2015 21:26:04 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1348</guid>
				<description><![CDATA[This is post 10 of 10 in the series &#8220;MongoDB&#8221; It&#8217;s taken me a year to write this MongoDB series, admittedly I have had a lot of down time, but this is the finale. One thing I&#8217;ve not given much explanation too, is the internals of MongoDB and how it works under, that what we&#8217;ll... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-10-tips-and-final-thoughts/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
	<p class="wp-post-series-name">
		This is post 10 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>

	
	</aside>
<h2>It&#8217;s taken me a year to write this MongoDB series, admittedly I have had a lot of down time, but this is the finale. One thing I&#8217;ve not given much explanation too, is the internals of MongoDB and how it works under, that what we&#8217;ll be covering here.</h2>
<p>The main internals I want to cover are, how Mongo actually manages it write concerns using locks and how journaling works. After that, I&#8217;ll probably ramble on for a bit and have a big emotional climax.</p>
<p><span id="more-1348"></span></p>
<h2>Locks</h2>
<p>MongoDB has a pretty expansive set of locks. When I fist started this series, the latest version of MongoDB was 2.6, if I remember correctly, now version 3.2 is the latest. The internals between version 2 and 3 changed a hell of a lot and these changes have propagated down to the locks.</p>
<p>One of the major changes between version 2 and 3 was the switch between the default storage engine. Previously MMAPv1 was the default, now <a href="https://docs.mongodb.org/manual/core/wiredtiger/#storage-wiredtiger">WiredTiger</a> is the default. The changes between these storage engines is sufficient enough to warrant its own blog post, but I&#8217;m going to focus the best new feature of the bunch; document level concurrency.</p>
<p>Document level concurrency, allows MongoDB to put a lock on any document in any collection. Previously to version 3 of MongoDB, this wasn&#8217;t possible and a lock would have to be put on the entire collection for every write. Obviously this is a humongous improvement.</p>
<p>You can get a list of all locks which are current set on your database by running:</p>
<pre class="prettyprint linenums">
db.currentOp()
</pre>
<p>You can get a list of all existing locks by running:</p>
<pre class="prettyprint linenums">
mongotop --locks
</pre>
<p>Apart from the document locks which are created when performing CRUD operation, there are a bunch of operations and commands that will lock up an entire database, lets cover some of these:</p>
<ol>
<li>Compact &#8211; Used to reclaim disk space.</li>
<li>Repair &#8211; Used when journaling is disabled and there is a bad shutdown causing data to corrupt.</li>
<li>MapReduce &#8211; Used to perform complicated queries across a cluster.</li>
<li>Copying a database</li>
<li>Journaling to disk from memory creates a system wide lock for a short interval.</li>
</ol>
<p>For more information on lock, check out the <a href="https://docs.mongodb.org/manual/faq/concurrency/">MongoDB concurrency docs</a></p>
<h2>Journaling</h2>
<ol>
<li>Every write to a mongod is first to send to an in memory journal</li>
<li>After 100ms (configurable), journal entries are then written to a disk journal on disk in$DB_PATH/journal/*, so in the event of a crash, no more than 100ms of data will be lost.</li>
<li>Data is read from the Journal on disk and written to the database every 60 seconds or after 2GB of journal entries are written, whichever comes first.</li>
<li>Journal files are removed after a clean shutdown.</li>
<li>On a crash of MongoDB, mongod will replay the journal on reboot.</li>
<li>Journaling can be disabled, however if you have a hard crash you may get corrupt data on when using the MMAPv1 storage engine. The WiredTiger storage engine is slightly more intelligent and uses a checkpoint system, so in the event of a hard crash, you will not get corrupt data but you will lose some data. For these reasons it is never advised to have journaling disabled and for that reason, I&#8217;m not even going to tell you how to disable it.</li>
</ol>
<p>The write to the disk journal every 10ms instead of every 100ms, you would run</p>
<pre class="prettyprint linenums">
db.adminCommand({ "setParameter": 1, "journalCommitInterval": 10 })
</pre>
<h2>The flow of MongoDB writes</h2>
<p>This is a very complicated subject and one which rightly deserves it’s own chapter in a book. Fortunately I haven’t written a MongoDB book, but I’m going to explain in as simple terms as I can, how the flow of how writes are sent from your client to actually be saved in your cluster.</p>
<ol>
<li>Your application server wants to update a users name, it opens a connection to one of your mongos servers and sends the write.</li>
<li>The Mongos will look inside the config servers, to work out which shard should store the information. Once the Mongos has located this information, it will send the write to the primary node in that shards replica set.</li>
<li>The write is received by the MongoDB wire protocol, this is essentially a TCP/IP socket for mongod.</li>
<li>The socket will communicate with mongod and start the journalling process, starting with the memory journal and then the disk journal, as described above.</li>
<li>Every minute (customisable) the disk journal is written to the database and oplog.</li>
<li>Secondary nodes will suck data from their source and update their oplog. This can happen at any time, depending on how busy the secondaries are.</li>
</ol>
<p>It&#8217;s a pretty complicated process and there are a bunch of configurations that can interfere with these process. On top of that you might not be using shards or replication which seriously simplifies the process. I might actually write a separate post to go over this in detail.</p>
<h2>Config Servers</h2>
<p>Config servers are required as soon as you start using shards to scale out your database. The config servers are used to store information about where you data resides in the cluster, which nodes you have in the cluster, the status of these nodes and general setting thats your mongod and mongos nodes should adhere too.</p>
<p>Your applications should ideally always have 3 config servers, to prevent data loss, each server should reside on a separate machine, however they can be low powered machines or even the application servers if you budget doesn&#8217;t stretch for separate servers. A config server is simple tailored mongod which is started with the &#8211;configsvr flag.</p>
<p><pre class="prettyprint linenums">
mongod --configsvr --dbpath /var/lib/mongodb -f /var/lib/config/mongod.conf
</pre>
<h2>Drum Roll</h2>
</p>
<p>And that&#8217;s a wrap. As I mentioned above, when I first started this series, MongoDB version 3 wasn&#8217;t released. Thankfully, despite the internals having been completely re-engineered, the consumer API has stayed almost identical. There&#8217;s probably the odd function which has been renamed or the odd parameter which has been meddled with, but I&#8217;ve gone through my old posts and updated most of them.</p>
<p>Like I said above, in time I might write up a detailed post about how the internal of writing works within MongoDB, with all the varieties of configuration and architecture. For now, the details above along with all my posts, you should be enough for the average user.</p>
<p>As always, thanks for reading.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-10-tips-and-final-thoughts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 9 – Deployments</title>
		<link>https://www.jakowicz.com/mongodb-part-9-deployments/</link>
				<comments>https://www.jakowicz.com/mongodb-part-9-deployments/#comments</comments>
				<pubDate>Sun, 29 Nov 2015 13:44:28 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1343</guid>
				<description><![CDATA[This is post 9 of 10 in the series &#8220;MongoDB&#8221; Welcome back. Deploying MongoDB isn&#8217;t difficult, but there are a tonne of tricks you can use to really optimise your database. That&#8217;s what were going to be covering in this post. I’m not going to be covering how to create clusters as I already covered... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-9-deployments/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
	<p class="wp-post-series-name">
		This is post 9 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>

	
	</aside>
<h2>Welcome back. Deploying MongoDB isn&#8217;t difficult, but there are a tonne of tricks you can use to really optimise your database. That&#8217;s what were going to be covering in this post.</h2>
<p>I’m not going to be covering how to create clusters as I already covered that in part 5 of the series &#8211; <a href="http://www.jakowicz.com/mongodb-part-5-sharding/">Sharding</a>. I’m not even going to discuss provisioning solutions like Puppet, Chef, Ansible etc. What I am going to discuss however, is a collection of system choices that need to be thought, about when creating your cluster. So let&#8217;s get started.</p>
<p><span id="more-1343"></span></p>
<h2>Storage</h2>
<p>If your budget stretches to affording SSD’s, it&#8217;s a great investment. The hard disk is the main bottleneck in any MongoDB setup. Using SSD’s or large amounts of memory will dramatically improve IO Wait, Lock times and CPU power usage.</p>
<h2>CPU</h2>
<p>MongoDB doesn’t require much CPU power, apart from when building indexes and occasionally when using MapReduce. A dual core CPU can easily handle 10k queries per second.</p>
<h2>Operating System</h2>
<p>MongoDB should really only be deployed on a Linux distribution. As much as MongoDb is supported on Windows and OSX, you’re asking for trouble using either in production.</p>
<p>Make sure you use a 64 bit OS always, otherwise your data directory will be limited to 2GB. Mongo 3, which was released about 6 months ago, is only supported on 64 bit systems.</p>
<p>Mongod instances can be split across multiple different OS’s, every OS uses the same wire protocol and stores data in the same manner.</p>
<p>MongoDB recommend running on a little-endian architecture. Basically all modern CPU’s are little-endian or bi-endian, which means they support little-endian and big-endian.</p>
<h2>RAID setup</h2>
<p>There are a bunch different RAID setups you could use to shard and replicate your data. These aren’t really necessary as MongoDB provides a far more customisable solutions to both sharding and replication. But here are a couple of options that you might want to consider.</p>
<ol>
<li>RAID0 &#8211; Data is split across multiple hard disks, this will result in data loss if a hard disk is to crash.</li>
<li>RAID1 &#8211; Data is replicated across all hard disks on the RAID. If a hard disk crashes, there will be no data loss.</li>
<li>RAID5 &#8211; All data is replicated onto at least 2 drives, so any drive can crash and data will still be available.</li>
<li>RAID10 &#8211; This is a mix of using both RAID0 and RAID1. Originally with a RAID0 to shard files and RAID1 to replicate each RAID0.</li>
</ol>
<h2>Swap Space</h2>
<p>MongoDB doesn’t normally require swap space, but it can be useful when building indexes and running repairs. Otherwise MongoDB may get killed by the OOM killer.</p>
<p>Here are some command you can use to create and start using a swap file.</p>
<pre class="prettyprint linenums">
# create a directory that will hold the swap file 
sudo mkdir -p /var/cache/swap/

# for 4GB storage, 1MB at a time 
sudo dd if=/dev/zero of=/var/cache/swap/myswap bs=1M count=4096

# Only root can access 
sudo chmod 0600 /var/cache/swap/myswap

# Make the swap file 
sudo mkswap /var/cache/swap/myswap

# Announce to system
sudo swapon /var/cache/swap/myswap

# Insert the following line in /etc/fstab for swap from the next boot:
/var/cache/swap/myswap none swap sw 0 0

# Turn off swap space if need be
sudo swapoff /var/cache/swap/myswap
</pre>
<h2>Filesystem</h2>
<p>If possible, ext4 or XFS should be used as they allow for filesystem snapshots. ext3 is not recommended, because MongoDB regularly creates zero-fill data files, which is slow and can freeze for minutes.</p>
<h2>Memory Overcommitting</h2>
<p>This happens when a process requests more memory than is available. If overcommitting is enabled the kernel will promise the memory in the hope that it’ll become available. This doesn’t work well with MongoDB, to disable overcommitting run</p>
<pre class="prettyprint linenums">
echo 2 > /proc/sys/vm/overcommit_memory
</pre>
<h2>NUMA</h2>
<p>Turn off NUMA (Non Uniform Memory Architecture)</p>
<p>NUMA is the term meaning each CPU has its own allocated memory. This is useful for day to day work, but in a MongoDB environment, it can result in your memory not being used effectively. NUMA should be disabled in your bios and MongoDB restarted.</p>
<pre class="prettyprint linenums">
# Updating Your bios (grub.cfg)
kernel /boot/vmlinuz-2.6.38-8-generic root=/dev/sda ro quiet numa=off

# Starting mongod with the numactl command
numactl --interleave=all mongod -f config.conf
</pre>
<h2>Update your readahead</h2>
<p>Read ahead is how much extra data should read into memory which wasn’t asked for. This can be useful for gathering data which might be required soon when you have large documents. However if you have small documents, you would probably want a smaller readahead. This will stop data being read into memory, which isn’t needed.</p>
<pre class="prettyprint linenums">
# To get a report of your readahead for each drive
# The RA column is your readahead and is measure in 512 bytes sectors.
# So a value of 256, means 256 * 512 bytes = 128kb readahead
sudo blockdev --report

# Update the readahead for /de/sdb3 to 16 * 512 bytes = 8kb
sudo blockdev --setra 16 /dev/sdb3
</pre>
<p>Readahead should not be set below 16 sectors (8KB), as this will make fetching indexes less efficient. Furthermore, it’s not recommended to set the readahead above 256 sectors.</p>
<h2>Hugepages</h2>
<p>Hugepages should be disabled. It designed for systems that do a lot of sequential reading, like relational databases. Hugepages can cause similar issues to a high readahead.</p>
<p><a href="http://www.oracle-base.com/articles/linux/configuring-huge-pages-for-oracle-on-linux-64.php#disabling-transparent-hugepages" target="_blank">Learn more about how to configure hugepages</a></p>
<h2>File descriptors</h2>
<p>The maximum number of file descriptors is configured to 1024 by default. This should be increased to unlimited or at least increased to around 20,000. Each incoming and outgoing request will use a file descriptor. So a file descriptor limit of 20,000, will allow roughly 10,000 concurrent connections.</p>
<pre class="prettyprint linenums">
# Unlimited file descriptors
ulimit -m 

# 20,000 file descriptors
ulimit -n 20000
</pre>
<h2>Firewalls</h2>
<p>Make sure each MongoDB node, can only be accessed by nodes that require them.</p>
<ol>
<li>Clients can connect to each mongos</li>
<li>Mongos can connect to all mongod data nodes &#038; config nodes</li>
<li>Mongod data nodes can connect to other mongod data nodes &#038; config nodes</li>
<li>Config nodes don’t need to connect to any MongoDB nodes</li>
</ol>
<h2>Make sure clocks are in sync</h2>
<p>If the clocks on your shards are not in sync you can have issues with replication. MongoDB can deal with slight discrepancies (up to a few minutes). Clocks can be kept in sync by using the <a href="http://doc.ntp.org/" target="_blank">ntp daemon</a>.</p>
<h2>Turn off periodic updates</h2>
<p>Turn off updates from package managers which can slow down the system unexpectedly. This should be managed with a proper configuration management tool anyway.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-9-deployments/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 8 – Backups</title>
		<link>https://www.jakowicz.com/mongodb-part-8-backups/</link>
				<comments>https://www.jakowicz.com/mongodb-part-8-backups/#respond</comments>
				<pubDate>Sun, 18 Oct 2015 18:09:15 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1336</guid>
				<description><![CDATA[This is post 8 of 10 in the series &#8220;MongoDB&#8221; Far too often do backups get overlooked. In this blog, I&#8217;ll explain all the ways of backing up your MongoDB databases along with some general backup tips. Before getting into the nitty gritty of backups, it&#8217;s important to remember that there are multiple MongoDB setups... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-8-backups/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
	<p class="wp-post-series-name">
		This is post 8 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>

	
	</aside>
<h2>Far too often do backups get overlooked. In this blog, I&#8217;ll explain all the ways of backing up your MongoDB databases along with some general backup tips.</h2>
<p>Before getting into the nitty gritty of backups, it&#8217;s important to remember that there are multiple MongoDB setups you could be running. For example, you could be running a standalone MongoDB instance, a replica set, or using shards. Regardless of which setup you are using, the backup process is practically identical.</p>
<p>One of the most important tips when creating backups, is to always use secondary nodes where possible. This will prevent your application from being inaccessible. If you to were backup a primary node, your application will be unable to receive writes, which is less than ideal to put it lightly.</p>
<p><span id="more-1336"></span></p>
<h2>Type of backups</h2>
<h3>Snapshots</h3>
<p>Depending on what OS and filesystem you are running, it may be possible for you to create system snapshots. This isn&#8217;t a MongoDB feature but can be accomplished using a tool called LVM on Linux. A snapshot is essentially a complete freeze frame of a file system at a certain point in time. This is easily to automate and requires zero downtime. Snapshots are also supported by Amazon&#8217;s, EBS volumes and on the Google Cloud Platform for free, allowing you to create and rollback from snapshots very quickly. Creating snapshots is said to have a O(1) complexity, which means regardless of the amount of data in the snapshot, the time to create it will remain constant. Creating snapshots on your own hardware can be more tricky, but it certainly worth the time investment.</p>
<h3>Manual Backups</h3>
<p>By manual backups, what I actually mean is backing up the directory which contains your data. It&#8217;s as simple as locking the data directory, so no further writes can be performed, copying your data directory to a backup location and then releasing the lock. It&#8217;s important to note that when locking the data directory, writes to all databases will be locked, not just writes to the database you are backing up. This is why backups should only be made on secondaries. If you&#8217;re running MongoDB on a single node without replication, you are unfortunately going to have some downtime while this happens.</p>
<pre class="prettyprint linenums">
// Locks all databases
db.fsyncLock()

// Copy data to a backup location
cp /data/db/* /backup

// Release database locks
db.fsyncUnlock()
</pre>
<p>To restore from a backup, you can follow this same process. Just copying data from your backup location to your mongo data location instead.</p>
<h3>Mongodump and mongorestore</h3>
<p>MongoDB has also provided two tool for you to backup and restore data, aptly names mongodump and mongorestore. Mongodump is slower than manual backups but also more customisable. There is no need to shut down your mongod instance or create any locks for this to work. Simply run mongodump and all of your databases will be dumped into a directory named dump, at your current location.</p>
<pre class="prettyprint linenums">
// The --oplog flag will make sure all operations that happen during the backup are replayed.
mongodump -p 27017 --oplog

// --oplogReplay must be used when --oplog flag is used in the mongodump
mongorestore -p 27017 --oplogReplay dump_dir

// It's also possible to just restore a specific collection into a specific db.
mongorestore --db newDb --collection coll dump/db/coll.bson
</pre>
<p>When a replica set member is being restored via mongorestore, the oplog collection must also be restored. Without the oplog collection, MongoDB will not know which version the node is on and what still needs migrating from the other nodes.</p>
<pre class="prettyprint linenums">
use local
db.createCollection("oplog.rs", {"capped" : true, "size" : 10000000})
mongorestore -d local -c oplog.rs dump/oplog.bson
</pre>
<p>The same version of mongodump and mongorestore should be used to avoid compatibility issues.</p>
<h3>Delayed secondary</h3>
<p>As I mentioned in the replica set post, it&#8217;s possible to create delayed secondary nodes, these are nodes which never serve reads or writes and always stay a certain amount of writes behind the primary node. This ensures that if your other nodes get corrupted. You&#8217;ll still have a relatively recent backup of the data. For more information on setting up delayed secondaries, check out the post I wrote on <a href="/mongodb-part-4-replication/">replication</a>.</p>
<h3>Backup shards</h3>
<p>Backing up shards can be tricky business, if you have the option, definitely go down the snapshotting route. It&#8217;s by far the best way to ensure there is no data loss.</p>
<p>Shards are also backed up just like standalone nodes and replica sets. This makes sense as that&#8217;s all a shard is anyway. Just you now have multiple shards, which are probably  replica sets in their own right. So what&#8217;s the problem. You can freeze one secondary in each replica at the same time and perform a manual backup or mongodump. This will give you an exact version of the data set at a specific point in time for all your shards. But there&#8217;s a problem!</p>
<p>Let&#8217;s assume, that you make backups every night at midnight. 8pm hits, 20 hours after your last backup and one of your shards vanishes off the grid. The warehouse burnt down. Shit.</p>
<p>You think you&#8217;re safe, but actually in the last 20 hours, any number of chunks could have moved on and off off that shard. What this means is some data which you think you&#8217;ve lost may have moved to another shard and some data you think was safe has moved to the missing shard. This means when recovering the 20 hour backup, you&#8217;re going to lose some data, unless no chunks have moved onto the node in the last 20 hours. Obviously you could look at the chunk movement logs, but it&#8217;ll be incredibly tedious and will no doubt result in some down time and lots of dev time wasted. This is why snapshotting is a better choice.</p>
<p>Another option is to permanently have the balancer off and manually balance your shards, which will prevent chunks from moving around automatically. I highly recommend this if you can’t use a snapshot backup approach.</p>
<p>Whatever approach you take, when performing a backup of a shard, you should first turn off the balancer, to prevent chunk moving around mid backup.</p>
<pre class="prettyprint linenums">
// Run from each mongos node to disable the balancer
sh.setBalancerState(false)
</pre>
<p>You can then continue to perform the normal backup procedure described above; Manual backups or mongodump. Don&#8217;t forget to backup the oplog too when using mongodump.</p>
<p>When backing up a shard you also need to make sure you backup one of your config databases using the command:</p>
<pre class="prettyprint linenums">
mongodump --oplog --db config
</pre>
<p>Without the config database, you will lose critical data, like which chunks reside on what shards. Lastly you need to re-enable the balancer on each mongos:</p>
<pre class="prettyprint linenums">
sh.setBalancerState(true)
</pre>
<h2>Conclusion</h2>
<p>If you&#8217;re using MongoDB, than you&#8217;re probably using shards too. If you&#8217;re using shards than you almost definitely want to make backups using snapshots. Either way backups are relatively simple and there’s no excuse for not setting them up immediately. Thanks for reading.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-8-backups/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 7 – MapReduce</title>
		<link>https://www.jakowicz.com/mongodb-part-7-mapreduce/</link>
				<comments>https://www.jakowicz.com/mongodb-part-7-mapreduce/#respond</comments>
				<pubDate>Sun, 14 Jun 2015 21:23:29 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MapReduce]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1304</guid>
				<description><![CDATA[This is post 7 of 10 in the series &#8220;MongoDB&#8221; MapReduce is a multi-step programming paradigm, which has been around for 2 decades. The goal of MapReduce is to break down a collection of data, sometimes from different machines on a network. Executing MapReduce jobs in parallel, over multiple machines, will significantly improve processing times.... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-7-mapreduce/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
	<p class="wp-post-series-name">
		This is post 7 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>

	
	</aside>
<h2>MapReduce is a multi-step programming paradigm, which has been around for 2 decades. The goal of MapReduce is to break down a collection of data, sometimes from different machines on a network. Executing MapReduce jobs in parallel, over multiple machines, will significantly improve processing times.</h2>
<p>The concept of MapReduce is inspired by the map and reduce functions in functional programming. When MapReduce was defined, it was as a 3 step process (Map, Shuffle, Reduce), MongoDB have taken this one step further and added a finaliser step. So lets see what’s involved in each step.</p>
<p><span id="more-1304"></span></p>
<h2>MapReduce Steps</h2>
<p><b>Map</b> &#8211; Maps every document in a collection with a key, value pair. What this means is, each document in a collection will be run through a map function individually and a new form of document should be emitted. This could be as simple as passing a document into a map function and multiplying a score value by 10. Think of map as being map one document to another document. Each document which is emitted should also have a key, which will be used in the shuffle and reduce steps.</p>
<p><b>Shuffle</b> &#8211; this takes the documents returned from the map step and aggregate them by their key, this assures each key has a single record which is mapped to multiple emitted values. This is done entirely in the background.</p>
<p><b>Reduce</b> &#8211; This step is used to break down the results of the shuffle step. The reduce function is run for every key that was emitted from the shuffle step. The reduce function is also passed a collection of the emitted values to aggregate.</p>
<p><b>Finaliser</b> &#8211; This is a final step, it will receive the output from the reduce step and perform one further reduce on it before returning the response to the client. This step is optional.</p>
<h2>Using MapReduce</h2>
<p>Using MapReduce is actually pretty simple, you need to define your map, reduce and maybe finalise functions and then execute them using the runCommand method.</p>
<pre class="prettyprint linenums">
db.runCommand({"mapreduce" : "collectionName", "map" : mapFunction, "reduce" : reduceFunction})
</pre>
<h2>Example MapReduce</h2>
<p>Search all documents in a collection and find every field name being used.</p>
<pre class="prettyprint linenums">
// This map is called for each document in the collection
map = function() {
    // Loop over each field in the collection
    for (var key in this) {
        // For each field, emit is called with the field name as the key and {count : 1} as the value.
        emit(key, {count : 1});
    }
};

// This is run for every field name that the map function found.
// key = field name, emit = A collection of {count : 1} objects
reduce = function(key, emits) {
    total = 0;
    for (var i in emits) {
        total += emits[i].count;
    }
    return {"count" : total};
}

// This outputs a bunch of information about, if the MapReduce was successful, a  collection name, where the result can be found, among other things.
db.runCommand({"mapreduce" : "collectionName", "map" : map, "reduce" : reduce})
</pre>
<h2>MapReduce Keys</h2>
<p>When running MapReduce jobs it can be useful to pass along additional keys, other than map and reduce, below are so of the most useful keys:</p>
<p><b>finalize</b> &#8211; This takes a function with the signature finalize(prev). This is called for each value returned by the reduce function, it can be used to further reduce the response.</p>
<p><b>keeptemp</b> &#8211; Takes a boolean value. Should the collection containing the response be kept, by default it will be removed when the connection is closed.</p>
<p><b>out</b> &#8211; The name of the collection, where the response should be saved. Setting this key, will automatically set keeptemp to true.</p>
<p><b>query</b> &#8211; Takes an object literal of criteria for data selection e.g. { “name” : “simon” }</p>
<p><b>limit</b> &#8211; The amount of documents you want to select.</p>
<h2>MapReduce Tips</h2>
<p>The output from a maps emit, must be the same as the response from a reduce. This way the output from 1 reduce step can be sent into another reduce step.</p>
<p>MapReduce is slow and should not be used with real time data</p>
<h2>Aggregation functions</h2>
<pre class="prettyprint linenums">
// Total documents in a collection
db.collection.count()

// Get every distinct age in the users collection
db.runCommand({"distinct" : "users", "key" : "age"})
</pre>
<h2>Conclusion</h2>
<p>MapReduce is a powerful very powerful concept within computer science. There are books devoted to just this subject and the fact that it&#8217;s still around after 20 years proves its credibility. Just be careful not to get stuck in the one size fits all trap also aptly named the golden hammer antipattern. MongoDB is a great all round database, but MapReduce isn&#8217;t its strongest feature. If crunching huge amounts of data is what your doing, you may be better off using Apache Hadoop or something similar.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-7-mapreduce/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 6 – GridFS</title>
		<link>https://www.jakowicz.com/mongodb-part-6-gridfs/</link>
				<comments>https://www.jakowicz.com/mongodb-part-6-gridfs/#respond</comments>
				<pubDate>Sun, 17 May 2015 13:40:48 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[GridFS]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1299</guid>
				<description><![CDATA[This is post 6 of 10 in the series &#8220;MongoDB&#8221; If you could have a wild guess at what GridFS is used for, you’d probably say some kind of file system and you wouldn’t be completely wrong. On the contrary, GridFS isn’t actually a filesystem, but rather a convention for storing large binary data files... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-6-gridfs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
	<p class="wp-post-series-name">
		This is post 6 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>

	
	</aside>
<h2>If you could have a wild guess at what GridFS is used for, you’d probably say some kind of file system and you wouldn’t be completely wrong. On the contrary, GridFS isn’t actually a filesystem, but rather a convention for storing large binary data files inside MongoDB.</h2>
<p>I haven’t covered storing binary data in MongoDB yet, however it&#8217;s possible to store binary data in standard documents, without using GridFS at all. This is possible using the BSON type BinData. It’s not very well supported by the mongo client, however most language drivers have good support, just google “MongoDB <language> BinData”. This is all well and good, in fact if you’re storing under 16MB of data per file, it’s recommended to use this approach. If however you are storing binary files larger than 16MB, GridFS is the way to go. 16MB is the maximum size of a document in MongoDB.</language></p>
<p><span id="more-1299"></span></p>
<h2>GridFS Intro</h2>
<p>By using GridFS, your binary files will automatically be broken up into smaller chunks which can be examined individually. This means there will be 2 collections, one to store the actual chunks and one to store the metadata which states which chunks relate to one another. These collections are named <a href="http://docs.mongodb.org/manual/reference/gridfs/#gridfs-chunks-collection">fs.chunks</a> and <a href="http://docs.mongodb.org/manual/reference/gridfs/#gridfs-files-collection">fs.files</a> respectively.</p>
<h2>Sharding</h2>
<p>In most situations, you&#8217;re probably not going to need to shard your binary files. However if you do, you&#8217;re going to want to shard using the files_id field on the fs.chunks collection. Doing so will make sure all chunks of the same file are stored on the same shard.</p>
<p>Be carful not to mix up shard chunks and GridFS chunks. Shard chunks are small collections of documents which all reside on a single shard. GridFS chunks are basically a single chunk of binary data that makes up part of a larger file.</p>
<h2>Replication</h2>
<p>You might be thinking, how does replication fit into this new data type. Well, actually it works just like any other data you have stored in documents. As long as you have nodes connected via a replica set, MongoDB will automatically replicate your binary data, just like it replicate everything else.</p>
<h2>Mongofiles</h2>
<p>In part one, I wrote about how MongoDB follows the unix philosophy of creating small tools that do one thing and do it well. Well on that note, when you install MongoDB, another tool you&#8217;ll get is called mongofiles. This tool is super simple to use and allows you to easily copy binary files into your database. Mongofiles generally takes most of the flags that the mongod tool uses, for example using flags like &#8211;hostname to connect to a specific host, or &#8211;port to connect to a specific port. You must also provide a -d flag which tells mongofiles the database you want to store these binary files in.</p>
<p>Here are some example mongofiles command</p>
<pre class="prettyprint linenums">
// Upload the foo.txt file to the reporting database
mongofiles -d reporting put foo.txt

// List all files in the reporting database
mongofiles list

// Download the foo.txt file from the reporting database
mongofiles get foo.txt

// Delete the foo.txt file from the reporting database
mongofiles delete foo.txt
</pre>
<h2>Conclusion</h2>
<p>It feels good to have such a short but sweet MongoDB blog, but that pretty much covers what you need to know. Make sure you can differentiate between shard and GridFS chunks as they are very different things. Most languages that you would dream of programming in, have support for using GridFS too, making it really easy to get started with. Until next time, where I&#8217;ll be discussing all things Map Reduce.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-6-gridfs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 5 – Sharding</title>
		<link>https://www.jakowicz.com/mongodb-part-5-sharding/</link>
				<comments>https://www.jakowicz.com/mongodb-part-5-sharding/#respond</comments>
				<pubDate>Tue, 05 May 2015 22:34:41 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Chunks]]></category>
		<category><![CDATA[mongo config]]></category>
		<category><![CDATA[mongod]]></category>
		<category><![CDATA[mongos]]></category>
		<category><![CDATA[Scaling]]></category>
		<category><![CDATA[shard keys]]></category>
		<category><![CDATA[Sharding]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1285</guid>
				<description><![CDATA[This is post 5 of 10 in the series &#8220;MongoDB&#8221; Sharding, the art of scalability. That’s a bold statement, after all, there are two very important arts to scalability. What shards allow you to do however, is to scale out. What this means is, you no longer need to keep all of your data on... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-5-sharding/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
	<p class="wp-post-series-name">
		This is post 5 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>

	
	</aside>
<h2>Sharding, the art of scalability. That’s a bold statement, after all, there are two very important arts to scalability. What shards allow you to do however, is to scale out. What this means is, you no longer need to keep all of your data on one hard drive or machine, heck not even in the same warehouse or continent. You can have unlimited machines in unlimited geographic locations, connected together and serving data as if it was all the data was stored in one central location.</h2>
<p>If you’re not already familiar with the terms scaling up/vertically and scaling out/horizontally, carry on reading. Otherwise you can skip the next few paragraphs.</p>
<p><span id="more-1285"></span></p>
<h2>Scaling Up/Vertically</h2>
<p>Scaling up is a concept, which is purely hardware based, You don’t need to modify the way in which you use your software. All you have to do is beef up your machine e.g. Throw in a swanky new SSD, an octuple core CPU and some extra memory and you’ll be scaling up like a seasoned professional.</p>
<p>tl;dr: Scaling up means beefing up your existing nodes.</p>
<h2>Scaling Out/Horizontally</h2>
<p>Scaling out on the other hand, is a completely different ball game. Irrespective of what DBMS you are using, you have to make some changes to your architecture to achieve scaling out. Scaling out in MongoDB is known as sharding, what sharding allows you to do, is split chunks of data across an unlimited number of nodes, over a network.</p>
<p>tl;dr: Scaling out means adding more nodes to share the load.</p>
<h2>Sharding 101</h2>
<p>Up until now, in this crash course of MongoDB, all we have used is mongod. Before we can start using shards, we need to add two new mongo tools to our toolbox: mongos (mongo shard) and another type of mongod for config servers.</p>
<p>Until I get onto what exactly a shard is in its full glory. Just think of a shard as either a single node or a replica set which stores data. If you have one shard, it will contain 100% of the data set. If you have two shards, the data will be split across both, what data gets saved on which shards is customisable, so data won&#8217;t necessarily be split 50:50.</p>
<p>In the below section I’m going to detail the basics of starting a mongo shard, using 3 config servers and a single shard, the shard will consist of a replica set of 2 nodes. There are a few steps here, so lets break it all down:</p>
<ol>
<li>Start 3 mongod config instances.</li>
<li>Start a mongos instance, and tell it where to find each config server.</li>
<li>Start 2 mongod nodes and create a replica from them.</li>
<li>Connect to the mongos and add the replica set as a shard.</li>
<li>Read that one more time, it&#8217;s important you understand it fully.</li>
</ol>
<h3>Step 1: Start Config servers</h3>
<p>Config servers are used to store shard metadata, like what mongo shards exist, which locks are on which databases, which shards contain what chunks, which nodes contain what data, among other things.</p>
<p>Mongod config servers are standard mongod instances which are started with the &#8211;configsrv flag. Config servers by default run on port 27019 and their data resides in /data/configdb. These can both be changed with the &#8211;port and &#8211;dbpath flags respectively. You should have 3 config servers running on different machines in production environments at all times. On non-production environments, it’s safe to have all 3 mongod config servers running on the same machine. Whether or not the mongod config servers are on the the same machine or not, they must all be able to communicate with each other, so make sure your firewall is appropriately configured.</p>
<pre class="prettyprint linenums">
mongod --configsvr --dbpath /data/configdb1 --port 27019
mongod --configsvr --dbpath /data/configdb2 --port 27020
mongod --configsvr --dbpath /data/configdb3 --port 27021
</pre>
<h3>Step 2: Start Mongos instances</h3>
<p>Mongos instances as you probably guessed, stands for mongo shard. However that&#8217;s a little misleading. Your shards are the actual data nodes &#8211; the mongod data nodes. Mongos does not store any of your data, all it does is route requests to your data nodes, sort of like a load balancer, there is one huge gaping difference though. Load balancers attempt to evenly distribute read and write loads, mongos does not. Mongos will only distribute reads loads, to the nodes which contain the data you require. For writes it will send the request to the node where your configuration states the data should be stored. You can completely configure where different chunks of data should be stored by creating shard tags. I&#8217;ll cover both tags and chunks below.</p>
<p>When starting a mongos instance, a complete set of config servers should be provided. Lets assume all of the config servers and mongos instances are started on localhost. We would start a mongos by running:</p>
<pre class="prettyprint linenums">
mongos --configdb localhost:27019,localhost:27020,localhost:27021 --port 17022
</pre>
<h3>Step 3: Start 2 Mongod nodes in a replica set</h3>
<p>Please see my <a href="/mongodb-part-4-replication">Mongo Replication article</a>, to find out how to start a replica set. For the purpose of this article I&#8217;m going to assume both mongod instances are started on localhost using ports 27017 and 27018 and the replica set is named rs0 using the &#8211;replSet flag.</p>
<h3>Step 4: Add replica set as a shard</h3>
<p>The final step is to add the replica set you just created, as a shard. This is done by connecting to our mongos instance using the mongo binary and executing the sh.addShard() method. If you have multiple mongos instances, you only need to run the below on one of them. The change will automatically propagate via the config servers.</p>
<pre class="prettyprint linenums">
// connect to our mongos
mongo --host localhost --port 27022

// Add the two nodes from a replica set as a shard.
db.runCommand({ addShard: "rs0/localhost:27017, localhost:27018", name: "shard_name" });
</pre>
<p>As i mentioned above, you could add a single node as a shard too, by running:</p>
<pre class="prettyprint linenums">
db.runCommand({ addShard: "localhost:27017", name: "shard_name" });
</pre>
<p>The shard name is important, we’ll use this later.</p>
<p>Despite single node shards being possible, you’re better of using a replica set always, even if you only have one node in the set. Otherwise if you decide to use a replica set in the future, it&#8217;s going to be a pain in the ass.</p>
<h2>Enabling sharding</h2>
<p>You’re probably thinking, that after getting this far, surely sharding is now enabled. But you would be wrong. What you&#8217;ve actually done is merely created a shard and told it which replica set to use for CRUD. Shards can contain numerous databases, each with multiple collections. The next logical step is to enable sharding on the databases we want to shard. Connect to any of your mongos nodes and run the following:</p>
<pre class="prettyprint linenums">
sh.enableSharding("&lt;database&gt;")
</pre>
<p>Next you need to decide how you want to shard your collections. This is where the real magic happens, collections are the things which actually contain data after all. By sharding a collection, what you are saying is to split the data in that collection across multiple replica sets. Doing so allows you to scale out.</p>
<p>Sharding a collection, takes a little more thought than sharding a database. What I mean by this, is that you need to decide which fields you want to shard on, or split on if you will. You can shard by any number of fields and by any fields you want.</p>
<p>When choosing which field or fields to shard on, you want to make sure related documents are stored on the same shards. A example of this could be storing records by region. Assume you was building a small social network. It might make sense to store all users from Europe on one shard and all users from Asia on another shard. The benefit here would be that most users in Europe would have friends in Europe, so when getting a list of friends, most of the time only one shard would have to be queried. If more than one shard needs to be queried, this will happen for you automatically, however you should try to limit these queries.</p>
<p>You can think of shard key internals like indexes, after all for a shard key to exist, the same key must first exist as an index. If the index doesn’t already exist when a collection is sharded, the index will be created automatically.</p>
<pre class="prettyprint linenums">
// Shard on the region field on the user collections.
// So if the values were either Europe, Asia, N America, S America, Africa, Australia, Antarctica.
// This shard would make sure all users with the same region are stored on the same replica set
sh.shardCollection(“db.users”, { region: 1 })

// Shard on two columns: region and language.
// This would make sure all users with the same region and language are stored on the same replica set
sh.shardCollection(“db.user”, { region: 1, language: 1})
</pre>
<p>It&#8217;s always best to have shard keys with a high cardinality.</p>
<h2>Shard Tags</h2>
<p>In the above “Sharding 101” section, I mentioned tags on a few occasions, but I’ve not gone any further than that. What I did cover, was how to shard collections. What you can’t do when initially sharding a collection, is decide which documents should be saved in which replica sets. This is where tags come in.</p>
<p>Tags allow you to get around this by first assigning tags to your shards and then assigning tags to field values or ranges, mongos will use these tags to decide where to write and read data from.</p>
<p>That sounds bloody confusing I know, so here&#8217;s an example:</p>
<p>Lets assume you have a collection called profiles, which contains a field called rank. The lower the rank, the more popular the profile is and the more often it is viewed. Lets assume that the collection has already been sharded on the rank field. You have 2 shards one which uses spinning disks and one that uses SSD’s. It would make sense to always store the most popular records on SSD, so they can be fetched quicker. Lets do that:</p>
<pre class="prettyprint linenums">
// Add a tag called ssd to the shard called ssd_shard_name. 
// Remeber, the shard name was decided when the shard was created.
sh.addShardTag(“ssd_shard_name”, “ssd”)

// Add all records with a rank between 1 and 100 to any shard with an ssd tag
sh.addTagRange(“db.profiles”, { “rank”: 1 }, { “rank”: 100 }, “ssd”)
</pre>
<p>If tags are changed on a shard, documents which no longer match the tags will automatically be migrated to a shard that do. If no nodes support them, they will not move.</p>
<pre class="prettyprint linenums">
// If you want to make sure all documents are saved to a specific shard, you can use the MinKey and MaxKey values
sh.addTagRange(“db.profiles”, { “rank”: MinKey }, { “rank”: MaxKey }, “ssd”)
</pre>
<h2>Chunks</h2>
<h3>What Are chunks</h3>
<p>Chunks are another topic I’ve mentioned and they’re another very important aspect of sharding. Chunks are exactly what they say on the tin &#8211; a chunk of a shard. Lets go back to the example above, where we created a shard key on the user collection and the region and language fields:</p>
<pre class="prettyprint linenums">
sh.shardCollection(“db.user”, { region: 1, language: 1 });
</pre>
<p>I said above, that this shard key will mean every document with the same region and language will reside on the same replica set. That is true, but we can actually go a little more granular. What it actually confirms, is the documents will reside on the same chunk.</p>
<p>Generally each shard key should have a very high cardinality or even better, be completely unique. Chunks don’t just contain identical values though, they group data by ranges (numerically or alphabetically). Lets assume you have 2 regions and 10 languages. That means there are 20 different permutations of shard key and therefore a maximum of 20 chunks can be created. That isn&#8217;t really ideal, as I mentioned above. Share keys should have a high cardinality or be unique. With only 20 possible permutations of shard key, there is the potential for chunks to grow huge because they cannot be broken down any further. This will make it difficult to scale out.</p>
<p>Also just because there is a maximum of 20 chunks, it doesn’t mean there will be 20 chunks. In fact to begin with there will be only 1 chunk and as you data set grows, your mongos daemons will try to split the chunks to make them smaller. If shard keys are unique or have a high cardinality, it means the mongos daemons will easily be able to break down chunks.</p>
<h3>How are chunks created?</h3>
<p>As soon as you start using shards, you no longer send reads and writes to individual nodes. Instead you connect to a mongos and the mongos sends the request to the correct shards. When you send the first write to a collection on each shard, the mongos will create a brand new chunk. All further writes will then be part of that chunk. Each mongos will individually keep track of how big chunks are getting on each shard. After receiving a certain number of writes, the mongos will ask the mongod to try and split the chunks into smaller chunks. The mongod will return a bunch of split points to the mongos and the mongos will then send the new chunk ranges to the config servers for saving. No data is moved at this point just chunks are broken down, so you have smaller and more manageable sets of data.</p>
<p>Chunks are automatically evenly distributed across all of your shards, unless you have tags setup to store them differently. If you remove shard tags, the mongos nodes will slowly try to move chunks between shards to evenly distribute them.</p>
<h3>Chunks and config servers?</h3>
<p>When a chunk is split into multiple smaller chunks, data isn’t actually moved. All that happens, is the config servers which store the different chunk ranges updates itself, to represent the new chunk ranges.</p>
<p>For a chunk to be split successfully, all config servers must be online and accessible. If a config server isn&#8217;t available, a split will be attempted after each write request to a mongos which has reached its threshold.</p>
<p>The amount of writes a mongos has to receives, before it asks the mongods to provide split points will vary. It depends mainly on the size of your collections. Unfortunately this value isn&#8217;t customisable.</p>
<h3>Balancing rounds</h3>
<p>A balancing round is when a mongos checks its threshold to see if it needs to ask the shards for split points in its chunks. Any mongos can run a balancing round, but only one mongos can run it at a time.</p>
<p>When a mongos becomes the balancer, it will create a balancer lock on the config database. The lock will stop other mongos nodes from becoming the balancer until the lock is freed. The lock is created on the config servers db.locks collection.</p>
<p>The balancer not only breaks down chunks, but can also move chunks between shards. Chunks will remain on the original shard and will continue to be served from the original shard until the chunk has been fully migrated. Once migrated mongos may try to route reads to the old shard for a while, this will silently fail and automatically route the request to the correct shard.</p>
<h3>Jumbo chunks</h3>
<p>If on one of your config servers you run:</p>
<pre class="prettyprint linenums">
db.settings.find({ _id: "chunksize" });
</pre>
<p>You’ll get a number, which is the maximum size of a chunk in megabytes, once a chunk exceed this size, it can no longer be split or moved without manual processes. These chunks are called jumbo chunks. A good chunk size is no bigger than 64MB. Having reasonably large chunks, will prevent your mongos nodes from constant splitting and moving of chunks around. If you decrease the chunk size. The chunks will not be split straight away. However when they are split they will trend towards the new size.</p>
<h4>Splitting and moving jumbo chunks</h4>
<p>You cannot split chunks which are greater than the max chunk size, without temporarily increasing max chunk size, or manually splitting a chunk using sh.splitAt() e.g.</p>
<pre class="prettyprint linenums">
sh.splitAt("db.users", {"user_id": 1234})
</pre>
<p>This will split the chunk containing the user with the user_id of 1234.</p>
<p>Jumbo chunks cannot be moved without increasing the chunk size, turning of the balancer and manually moving them.</p>
<pre class="prettyprint linenums">
// Turn of the balancer for the users collection
sh.disableBalancing(‘users’)

// Move the chunk containing the user with the user_id 1234, to the shard named shard2.
sh.moveChunk("db.users", { user_id: 1234 }, "shard2")
</pre>
<h2>Shard Keys</h2>
<p>When choose your shard keys, you want to carefully think about who is going to be primarily accessing the data and always trying to minimise the amount of shards required to perform an operation. Here are a couple of shard key types you could use:</p>
<h3>Ascending</h3>
<p>These use a field like _id that constantly gets larger. This means one shard gets all initial writes and are then chunked and moved, which is less than ideal in most situations, unless you&#8217;re attempting the firehose strategy.</p>
<h3>Randomly distributed</h3>
<p>These use fields, where data is inserted in no particular order e.g. email address, name, age. Randomly distributed fields are evenly(ish) distributed. MongoDB claims to not be as efficient accessing randomly distributed chunks. These are a very common choice.</p>
<h3>Location based</h3>
<p>These use a field like location or ip. This helps to keep records from similar regions, in the same chunks.</p>
<h2>Final Tips</h2>
<ol>
<li>Shard keys cannot contain arrays as each value in an array is individually indexed and so the values could reside on different shards and this can&#8217;t be stored in config.</li>
<li>Chunks are not physically grouped on disk just in metadata.</li>
<li>Shard keys cannot be geospatial indexes.</li>
<li>Shard keys should always have a high cardinality, this prevents jumbo junks. Smaller chunks are easier to move around and improves load balancing. A good way of increasing cardinality is using compound keys.</li>
<li>Once inserted, to change a shard key, the documents must be dropped and re-added.</li>
<li>There is a strategy called the firehose strategy, this is the process of sending all writes to a powerful shard, then moving the chunk afterwards.</li>
</ol>
<h2>Conclusion</h2>
<p>Three cheers, you made it. That was a lot to take in. You probably have a lot of questions and a lot of uncertainties about what you&#8217;ve just read. As always I&#8217;m more than happy to answer those question. Alternatively the MongoDB site will be able to expand further on all of the above. Thanks for reading.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-5-sharding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 4 – Replication</title>
		<link>https://www.jakowicz.com/mongodb-part-4-replication/</link>
				<comments>https://www.jakowicz.com/mongodb-part-4-replication/#respond</comments>
				<pubDate>Wed, 01 Apr 2015 14:17:53 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1239</guid>
				<description><![CDATA[This is post 4 of 10 in the series &#8220;MongoDB&#8221; CAP, the theorem behind MongoDB and most NoSQL databases, states that no distributed system can provide consistency, availability and partition tolerance. In this article I&#8217;m going to be writing about what MongoDB offers in the replication sector and how you can utilise replication to customise... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-4-replication/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
	<p class="wp-post-series-name">
		This is post 4 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>

	
	</aside>
<h2>CAP, the theorem behind MongoDB and most NoSQL databases, states that no distributed system can provide consistency, availability and partition tolerance.  In this article I&#8217;m going to be writing about what MongoDB offers in the replication sector and how you can utilise replication to customise all aspects of the CAP theorem.</h2>
<p>I&#8217;ll be covering: how to create replication sets, how replication works in MongoDB, how to configure individual nodes in a set, how to retrieve the status of nodes, how to configure write concern when executing queries and common CAP configurations.</p>
<p><span id="more-1239"></span></p>
<h2>Creating replica sets</h2>
<p>Creating replica sets in MongoDB is a pretty simple process, if you already have a running mongod instance, you&#8217;ll have to stop it first. Otherwise you can follow these instructions:</p>
<pre class="prettyprint linenums">
# Start each mongo daemon with the --replSet flag
# this flag provides the replica set name, each node must use the same name
mongod --replSet "rs0"

# Connect to the node you want to be the primary
mongo <hostname>

# Initialise the replica set
# This will make the current node a primary
rs.initiate()

# Add all secondary nodes to the set, it can take a few seconds for a node to connect to a cluster
# The port is optional and will default to 27017
rs.add("hostname:port")
rs.add("hostname:port")</hostname>
</pre>
<p>This is all well and good for development environments, but in production you&#8217;re going to want to use some kind of authentication, to prevent rouge nodes from accessing your cluster. MongoDB caters for this using the challenge-response authentication mechanism. It makes the process slightly more complicated, but MongoDB have some <a href="http://docs.mongodb.org/manual/tutorial/deploy-replica-set-with-auth/" target="_blank">fab docs</a>, telling you just what to do.</p>
<p>If you want to remove a node from a replica set, you can use the rs.remove() method.</p>
<pre class="prettyprint linenums">
rs.remove("hostname:port")
</pre>
<h2>How replication work</h2>
<p>Replication is the process of making sure data is mirrored across multiple nodes. These nodes could be running on the same machine or completely different ends of the earth. Ideally they&#8217;ll be somewhere in the middle of that e.g multiple warehouses and geographical locations. Replication works in MongoDB by linking multiple nodes together using the commands above. Once a collection of nodes are connected, one will be assigned as the primary and the others will be assigned as secondaries.</p>
<p>Each node is set a sync source, this essentially defines which node it should copy changes from. It&#8217;s usually a sensible option to have all nodes sync from the primary, however there are some benefits to having secondaries sync from other secondaries. Just be careful not to create large replication chains or even worse a replication loop. Every two seconds, every node in a replica set will ping every other member of the set to make sure they&#8217;re all still accessible and the cluster is still fully functional. If a node does not get a response from a ping within 10 seconds, the cluster will mark the node as inaccessible and the remaining nodes will attempt to continue without it. Once the node is accessible again it will automatically rejoin the replica set and start syncing missing changes.</p>
<p>You can update the sync source of a node by connecting to it then executing:</p>
<pre class="prettyprint linenums">
rs.syncFrom(“host:port”)
</pre>
<p>The magic behind replication is in what MongoDB calls the oplog. The oplog is a capped collection stored inside the local database (local.oplog.rs). Every node will have its own oplog containing it&#8217;s most recent changes. When a node pings its sync source every 2 seconds, it checks if there are any new changes to sync and if there are, it will automatically start syncing them. Once a node has synced a bunch of changes, it will add the changes to its own oplog. Then if that node is the sync source for any nodes, they can start syncing too. As I mentioned above, the oplog is a capped collection, what this means is the oplog will only store a certain amount of changes. The amount of changes is completely configurable and it&#8217;s recommended to store at least a weeks worth. Disk space is literally cheaper than chips, so you don&#8217;t have much to lose from having a huge oplog.</p>
<p>By default, MongoDB will create an oplog with a size equal to 5% of free storage. This can be overridden by starting mongod with the &#8211;oplogSize flag and the size in megabytes:</p>
<pre class="prettyprint linenums">
# Create a 1GB oplog
mongod --replSet "rs0" --oplogSize 1024
</pre>
<p>if you want to adjust the size of your oplog, the oplog collection must be dropped and recreated. Be very careful when doing this, not to lose changes which have not been synced elsewhere.</p>
<p>It&#8217;s important to note that in MongoDB only the primary node can receive write requests, however all nodes can be used for reading, regardless it&#8217;s almost always best to read from the primary. The sole purpose of replication, should be to prevent data loss in your application, remember only the primary node receives writes, so your secondaries may not necessarily be 100% up to date. If can afford to serve up slightly outdated data to your users, then you can potentially distribute read requests across your secondaries. As much as that probably sounds like a great idea, it&#8217;s rarely acceptable to serve up outdated data and there&#8217;s a much better way of dealing with scaling in the form of sharding, which will be discussed in a later article.</p>
<p>If you want to allow your secondary nodes to serve read requests, you can execute this command:</p>
<pre class="prettyprint linenums">
rs.slaveOk()
</pre>
<h2>Node configuration</h2>
<p>As much as it might look like MongoDB randomly picks a node to make the primary. It&#8217;s actually being intelligent and making sure it only allows one of the most up to date nodes to become the primary. This can be configured even further by setting a priority on each member of the set, MongoDB will then pick the node with the highest priority value and that is completely up to date. A member with a priority of 0 can never become the primary.</p>
<p>For a node to become the primary node, it must first request that it become the primary to the other nodes, this happens automatically when the node thinks it&#8217;s better suited as the primary than the current primary. All nodes will then vote on whether the node in contention should be elected as the primary or not. If any node vetoes the election, the primary will not be changed. A node will only veto when it thinks it should actually be the primary itself, in this case, it will then make a request itself to become the primary. Rinse, repeat.</p>
<p>The current node config can be retrieved by executing:</p>
<pre class="prettyprint linenums">
rs.config()
</pre>
<p>This will return some JSON containing a list of replica set members. You can edit the JSON (e.g. to set priority) however you like and reconfigure the nodes using the below options.</p>
<pre class="prettyprint linenums">
# The config variable is essentially the edited version of rs.config()
rs.reconfig(config)
</pre>
<p>Other useful config values you might want to set, include:</p>
<ol>
<li><b>buildIndexes</b> &#8211; If the node should create indexes. Nodes with buildIndexes set to false should also have a priority of 0 is it can never become the primary. Disabling buildIndexes can be useful on backup servers.</li>
<li><b>tags</b> &#8211; Tags assigned to the node, these tags can be used with WriteConcern, e.g. write to all node with the tag SSD. More on this soon.</li>
<li><b>slaveDelay</b> &#8211; The number of seconds a secondary should always remain behind its sync source. This is very useful as a contingency against data corruption or destruction.</li>
<li><b>hidden</b> &#8211; If hidden, the node cannot be used for reads. Hidden nodes are useful for backing up databases and for nodes running with a slaveDelay.</li>
<li><b>arbiterOnly</b> &#8211; If true the node is an arbiter. More on this soon.</li>
<li><b>vote</b> &#8211; Should the node be able to vote when a primary node is being elected. This should be boolean. A maximum of 7 nodes in a set are allowed to vote.</li>
</ol>
<h2>Arbiters</h2>
<p>Arbiters in MongoDB, as you can probably guess are just like arbiters in the real world, they are used to settle disputes. But what kind of disputes you might ask? When there is a partition between nodes, arbiters help to resolve this by giving the final vote as to who should be the primary, this does mean it&#8217;s only worth having an arbiter, if you have an even number of data nodes. The reason for this is that if there is an odd number of data nodes, there will already be a natural winner and adding an arbiter would actually go against you. Arbiters are not data nodes, so cannot accept read requests, it&#8217;s common practice to have arbiters running on very low performance boxes or even an application server. The most common use of an arbiter is when there isn&#8217;t enough budget, to run 3 data nodes in replication.</p>
<h3>Using arbiters</h3>
<p>Arbiters nodes are started just like data nodes and are be added to a replica set similarly too. Lets take a look:</p>
<pre class="prettyprint linenums">
# Start a new mongo daemon
mongod --replSet "rs0"

# Connect to the primary and add the new arbiter to the set
rs.addArb("hostname:port")
</pre>
<h2>Tagging replica sets &#038; write concern</h2>
<p>Write concern is a concept which says how many nodes and sometimes which nodes in particular a write should be made too. Write concern can be set to any of these values:</p>
<ol>
<li><b>1</b> &#8211; Write to the primary only.</li>
<li><b>0</b> &#8211; No acknowledgement of a successful write is required. So just attempt to write to the primary.</li>
<li><b>Any other number (/d+)</b> &#8211; Make sure the write is successful on the primary and synced to n-1 secondary nodes.</li>
<li><b>majority</b> &#8211; Make sure that at least 50% of voting members have been written too.</li>
<li><b>&lt;tag set&gt;</b> &#8211; Makes sure the specified tagged nodes are written to. Described below.</li>
</ol>
<h3>Creating and using tags</h3>
<pre class="prettyprint linenums">
# Add tags to replica set members
conf = rs.config()
conf.members[0].tags = { "datacenter.east": "rack1"  }
conf.members[1].tags = { "datacenter.east": "rack2"  }
conf.members[2].tags = { "datacenter.west": "rack1"  }

# Create a write concern tag called east, which writes data too the 2 nodes tagged with datacenter.east
# Why this key is called getLastErrorModes, is beyond me.
conf.settings = { getLastErrorModes: { east : { "datacenter.east": 2 }}

# Save the new config
rs.reconfig(conf)

# Use the new "east" write concern tag to decide where to write too
db.users.insert( { name: "Simon" }, { writeConcern: { w: "east" } } )
</pre>
<h2>Statuses</h2>
<p>There are a bunch of methods you can use to get information on how your replica set is setup and how it is currently performing. Some of the most useful include:</p>
<ol>
<li><b>rs.printReplicationInfo()</b> &#8211; Get oplog size information on the primary.</li>
<li><b>rs.printSlaveReplicationInfo()</b> &#8211; Get oplog size information on a secondary. This tells you how far the node is behind the primary.</li>
<li><b>db.isMaster()</b> &#8211; Used to see if this is the primary node or a secondary node.</li>
</ol>
<h2>Maintaining nodes in a replica set</h2>
<p>Maintaining your nodes in MongoDB can be a tricky task. You have to make sure that when adding, removing or editing nodes, you don&#8217;t lose any data. Generally the best way to get around this, is by taking secondary nodes offline, one at a time and making changes. Once all of your secondaries have be adjusted, you can take the primary offline and make the change there. Some useful commands when performing maintenance include:</p>
<ol>
<li><b>rs.stepDown(seconds=60)</b> &#8211; Make a primary become a secondary for the amount of seconds provided. 60 seconds is the default.</li>
<li><b>rs.freeze(seconds)</b> &#8211; Prevent a secondary from becoming a primary for the amount of seconds provided. Alternatively the secondaries priority could be changed to 0.</li>
</ol>
<p>Another common approach in MongoDB, is to create a cronjob to put any slow secondary nodes into maintenance mode. Putting a node into maintenance mode, prevents reads being send to the node, allowing it to catch up on syncing changes. To put a node into maintenance mode, you must first connect to it and then execute:</p>
<pre class="prettyprint linenums">
db.adminCommand({ "replSetMaintenance": true });
</pre>
<p>You can disable maintenance mode again by executing:</p>
<pre class="prettyprint linenums">
db.adminCommand({ "replSetMaintenance" : false });
</pre>
<h2>Common CAP configurations</h2>
<p>The common notion with the CAP theorem is, you can only support 2 aspects of CAP at any time. While this isn&#8217;t strictly true, there are trade offs you should be aware of.</p>
<h3>Consistency Vs latency</h3>
<p>This is a very simple trade off, which will help you to understand the consistency vs availability trade off, which we&#8217;ll discuss next. The theory is that every time your database performs a write, you have to say which nodes you would like the initial save to replicate too. This could be 1 node or 50 nodes or anything in between, it&#8217;s up to you. The trade off is that if you save to just 1 node, you get a very quick response and so latency is low, however consistency is also low. If you have a failure on the single node with changes, you will lose them. Alternatively you could opt to make sure data is replicated to all 50 nodes, this would be very slow, but it would also mean even if 49 nodes failed, you wouldn&#8217;t lose any data. The write concern you choose, should largely depend on the requirements of the application.</p>
<h3>Consistency Vs Availability</h3>
<p>So we have already covered what consistency means, availability on the other hand means, how available the system is, for reads and writes. Think back to the example above, if you have 50 nodes and a write concern of just 1 node. You wont have consistency, but even if 49 nodes went down, your 1 surviving node could be made the primary and continue making writes. On the flip side, if you had a write concern of 50, all of the nodes would be consistent, however if 1 node goes down, the application will no longer be able to perform writes.</p>
<h3>Resolving conflicts after a network partition</h3>
<p>If there is a network partition and as a result, an out of date secondary becomes the new primary, there will unfortunately be conflicts between the new and old primary, when the network partition is resolved. In this situation the old primaries changes are rolled back. These can then be reapplied manually. Rollbacks can fail if there are over 300MB of data to rollback or over 30 mins of operation time. In this situation, the old primary will need to go through an initial sync again.</p>
<h2>Initial Sync</h2>
<p>Initial sync is a process which must be run on new and out of date nodes e.g. after a network partition is resolved &#8211; as above. Initial sync involves copying all of the data from one node onto a new node. While the sync is happening new changes could also be applied, data is synced again to pull the latest changes from the oplog. Indexes are then added, a final sync of changes from the oplog are then applied. It’s possible for their to be so many changes, that when the 2nd or 3rd sync happens from the oplog, there may have been changes which are not synced but have been removed from the oplog &#8211; as it&#8217;s a capped collection. This will make the sync fail. This can be overcome by making the oplog bigger or by using a more durable data import solution.</p>
<h2>Conclusion</h2>
<p>Phew, you exclaim. That was a lot to take in right? and I&#8217;m guessing you can&#8217;t remember half of it. Replication and MongoDB in general are not easy subjects to digest, for you to really learn this stuff you&#8217;re going to have to read this all again and probably again after that. If you didn&#8217;t the first time around, I suggest you try to follow along with what I describe. Start by spinning up a couple of mongod instances on you local machine, hook them up together, maybe chuck in an arbiter too. Setup the nodes to sync from and edit the config of your nodes. e.g. priority and tags. Once you have done all of this you can start sending writes to your MongoDB and see how they propagate throughout your nodes. Take nodes offline and monitor how your other nodes will automatically take on the primary role. Then you can start toiling with write concern, see how increasing consistency mean taking longer to perform writes or even completely preventing writes, when you have not enough nodes online. Once you have a firm grasp on how all of these concepts link together to form replication in MongoDB, you&#8217;ll be halfway to becoming the rockstar MongoDB user, you&#8217;ve always wanted to be. In the next article, I&#8217;ll be covering sharding, it&#8217;s going to be another big one, so don&#8217;t take off those glorious new golden DBA boots just yet.</p>
<p>Thanks for reading!</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-4-replication/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 3 – Indexes</title>
		<link>https://www.jakowicz.com/mongodb-part-3-indexes/</link>
				<comments>https://www.jakowicz.com/mongodb-part-3-indexes/#respond</comments>
				<pubDate>Sat, 21 Mar 2015 13:56:47 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1236</guid>
				<description><![CDATA[This is post 3 of 10 in the series &#8220;MongoDB&#8221; It has been a while since my last post on MongoDB, but I’m back and looking to finish off this series over the next 6-8 weeks (Edit: 6-8 months). Anyway, in this article I&#8217;m going to be covering all of the different types of indexes... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-3-indexes/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
	<p class="wp-post-series-name">
		This is post 3 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>

	
	</aside>
<h2>It has been a while since my last post on MongoDB, but I’m back and looking to finish off this series over the next 6-8 weeks (Edit: 6-8 months). Anyway, in this article I&#8217;m going to be covering all of the different types of indexes you can use in MongoDB</h2>
<p>Most of these you&#8217;ll have heard of before, providing you’ve used almost any other DBMS. I&#8217;ll be providing examples of how to create each index, when you would want to use them and at the end I&#8217;ll throw together a few must know tips.</p>
<p><span id="more-1236"></span></p>
<h2>The everyday index</h2>
<p>A standard index is the most common kind of index. They&#8217;re incredibly easy to create and use. Here are some of their properties:</p>
<ol>
<li>A standard index is created on a single key on all documents.</li>
<li>Creating an index applies to all documents in the collection that contain the key specified.</li>
<li>If a document does not contain the indexed key, the document will not be part of the index.</li>
</ol>
<h3>Creating a standard index</h3>
<pre class="prettyprint linenums">
db.user.ensureIndex({ country: 1 })
</pre>
<p>What the line above will do, is create an index on the country key in the user collection. As with indexes in other DBMS, it&#8217;s better to create an index on keys which have a higher cardinality (lots of unique values). You also want to make sure, you&#8217;re indexing keys which you most frequently query on. Indexes also work when using modifiers. Some modifiers however do not utilise indexes very well, I&#8217;ll cover those later.</p>
<p>Standard indexes are automatically used when running a query on MongoDB. The majority of modifiers will make use of indexes.</p>
<h2>Compound Index</h2>
<p>Compound indexes are another very common form of index. They&#8217;re created just like standard indexes. The only difference is that compound indexes are multi-key. This is useful when you frequently query on more than one key at a time. MongoDB will only make use of indexes when they&#8217;re defined in the same order they&#8217;re used in. Compound indexes are also implicit, which means if you have a compound index over three keys, in the order: birth_year, country, name. MongoDB will make use of the index when querying on all three keys, or birth_year and country, or just birth_year. This is exactly the same as in MySQL. Compound indexes are used automatically just like standard indexes.</p>
<h3>Creating a compound index</h3>
<pre class="prettyprint linenums">
db.users.ensureIndex({ birth_year: 1, country: 1, name: 1 })
</pre>
<h2>Covered Index</h2>
<p>Covered indexes aren&#8217;t really a type of index, but rather they&#8217;re compound indexes, which don&#8217;t require lookups to the actual collection, this happens when the index contains all of the data required. Covered indexes are used automatically.</p>
<h2>Unique Index</h2>
<p>These are similar to standard indexes, the only difference being that each record in the index must be unique. The null value must also be unique.</p>
<h3>Creating a unique index</h3>
<pre class="prettyprint linenums">
db.user.ensureIndex({ country: 1 }, { unique: true })
</pre>
<h2>Unique Compound Index</h2>
<p>By now you can probably guess what these are. If not just imagine a compound index where each collection of keys must be unique.</p>
<h3>Creating a unique compound index</h3>
<pre class="prettyprint linenums">
db.user.ensureIndex({ country: 1, name: 1 }, { unique: true })
</pre>
<p>In the above example, each pair of country and name keys, must be unique.</p>
<h2>Sparse Index</h2>
<p>These indexes are very useful to use alongside unique indexes. They allow you to create unique indexes, but with an unlimited number of null values. Sparse indexes also not return null values when running a &#8220;Not Equal&#8221; query like:</p>
<pre class="prettyprint linenums">
db.user.find({ name: { $ne: 'some-name' } })
</pre>
<h3>Creating a sparse index</h3>
<pre class="prettyprint linenums">
db.user.ensureIndex({ country: 1 }, { sparse: true })
</pre>
<h3>Creating a unique and sparse index</h3>
<pre class="prettyprint linenums">
db.user.ensureIndex({ country: 1 }, { unique: true, sparse: true })
</pre>
<h2>TTL &#8211; Time to live Index</h2>
<p>TTL indexes can be on single keys or compound keys, they can also be unique and sparse. The additional functionality they provide, is providing a life span in seconds for all documents.</p>
<h3>Creating a TTL index</h3>
<pre class="prettyprint linenums">
db.log.ensureIndex({ "lastUpdated": 1}, { expireAfterSeconds: 60*60*24 })
</pre>
<p>What this will do, is delete all documents from the log collection, once their lastUpdated value is more than 24 hours (60*60*24 seconds) in the past. You can probably imagine, just how useful this is in game development.</p>
<h2>Full Text Index</h2>
<p>These can be used to search for data inside a text value. Full text searches have to be enabled on each MongoDB node, before they can be used. This can be done by executing the below in a Mongo console:</p>
<pre class="prettyprint linenums">
db.adminCommand({ "setParameter": 1, "textSearchEnabled": true})
</pre>
<h3>Create compound full text index over 2 keys.</h3>
<pre class="prettyprint linenums">
db.user.ensureIndex({ job_description: "text", personal_profile: "text" })
</pre>
<h3>Create a full text index on every string field in the document, this will also search arrays which contain strings.</h3>
<pre class="prettyprint linenums">
db.user.ensureIndex({ $**: "text" })
</pre>
<h3>Using a full text index &#8211; Search for any of the 3 words provided.</h3>
<pre class="prettyprint linenums">
db.runCommand({ text: "use", search: "some search words" })
</pre>
<h2>Geospatial &#8211; 2dsphere</h2>
<p>These indexes can be used to search for records on a grid or a sphere using GeoJSON.</p>
<h3>Create a 2dsphere index</h3>
<pre class="prettyprint linenums">
db.places.ensureIndex({"tile" : "2dsphere"})

# The default grid is -180 to 180, this can be adjusted as below
db.places.ensureIndex({"light-years" : "2dsphere"}, {"min" : -1000, "max" : 1000})
</pre>
<h3>Using a 2dsphere index </h3>
<pre class="prettyprint linenums">
# Find objects near a tile
db.places.find({"tile" : {"$near" : [20, 21]}})

# Find objects within a box radius
db.places.find({"tile" : {"$within" : {"$box" : [[10, 20], [15, 30]]}}})

# Find object in a radius of 5 from a center point
db.places.find({"tile" : {"$within" : {"$center" : [[10, 20], 5]}}})

# Find objects within a polygon
db.places.find({"tile" : {"$within" : {"$polygon" : [[0, 1], [1, 2], [2, 3]]}}})
</pre>
<h3>Example 2dsphere document.</h3>
<p>When using 2dsphere indexes, the key that you make the index, must also contain an object with two keys called type &#038; coordinates. The type attribute defines the type of vector e.g. point, line, shape. The coordinates attributes states the points on the grid, where the object is located.</p>
<pre class="prettyprint linenums">
{ tile: {
    type: "MultiPoint",
    coordinates: [
       [ 1, 1 ],
       [ 1, 5 ],
       [ 5, 5 ],
       [ 5, 1 ]
    ]
  }
}
</pre>
<h2>Hashed Index</h2>
<p>Hashed indexes are different from normal indexes in that, instead of indexing the values. The hashed index will store a hash of the values in the index. Doing this helps to evenly distribute chunks across a shard. You can think of chunks as a collection of documents. Hashed indexes cannot be sparse or compound.</p>
<h3>Create a hashed index</h3>
<pre class="prettyprint linenums">
db.coll.ensureIndex({"country" : “hashed”})
</pre>
<h2>Useful index commands</h2>
<pre class="prettyprint linenums">
# Create an index in the background. 
# Creating indexes can be slow and puts a temporary lock on the table, which will prevents writes.
# To counter this, you can create an index in the background, the process will
# occasionally yield to allow writes to occur.
db.items.ensureIndex({ "amount": 1 }, { "background": true })

# Fetch a list of all on a collection and their names
# Index names are by default automatically generated
db.items.getIndexes()

# Drop an index by its name
db.items.dropIndex("indexName")
</pre>
<h2>Modifier that support indexes badly</h2>
<p>As I mentioned above, some modifiers do not play nicely with indexes, these are described below:</p>
<ol>
<li>$where &#8211; Cannot use indexes</li>
<li>$exists, $ne, $not &#8211; Little benefit to using indexes</li>
</ol>
<p>This may change in newer versions of MongoDB.</p>
<h2>Index Tips</h2>
<ol>
<li>Indexes should be created on one secondary at a time, by putting it in standalone mode. This will prevent you from locking up your primary node.</li>
<li>Once all secondaries have been updated, the primary should be updated, this can be done two ways:
<ol>
<li>Taking it into standalone mode and adding the index.</li>
<li>Create the index, in the background.
<ol>
<li>db.users.ensureIndex({ name: 1 }, { background: true })</li>
</ol>
</li>
</ol>
</li>
</ol>
<h2>Conclusion</h2>
<p>That pretty much gives a brief overview of all the different types of indexes available in MongoDB, as always the docs are fantastic if you want to learn more.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-3-indexes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 2 – Databases</title>
		<link>https://www.jakowicz.com/mongodb-part-2-databases/</link>
				<comments>https://www.jakowicz.com/mongodb-part-2-databases/#respond</comments>
				<pubDate>Wed, 10 Dec 2014 16:09:39 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1226</guid>
				<description><![CDATA[This is post 2 of 10 in the series &#8220;MongoDB&#8221; OK. So in part 1 we covered a bunch of MongoDB basics. In this part, I plan on covering in detail the core MongoDB databases, what collections they have and what they&#8217;re used for. When you first install MongoDB, two databases are created for you... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-2-databases/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
	<p class="wp-post-series-name">
		This is post 2 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>

	
	</aside>
<h2>OK. So in part 1 we covered a bunch of MongoDB basics. In this part, I plan on covering in detail the core MongoDB databases, what collections they have and what they&#8217;re used for.</h2>
<p>When you first install MongoDB, two databases are created for you called admin and local. They don&#8217;t contain many collections and may not even contain any to begin with, however don&#8217;t worry about this, Mongo will create them as an when it needs them.</p>
<p>The third core database is called config. Config databases are a little more complicated, in that they can only be accessed when connected to a shard instead of a particular daemon. I haven&#8217;t covered shards yet. But for now just think of shards as individual mongod nodes, that all together form your data set. How this happens is very customisable, these customisable setting are stored in the config database. I&#8217;ll cover shards in great detail in a separate post.</p>
<p class="edit"><span>Edit:</span> <a href="/mongodb-part-5-sharding/">Learn about MongoDB shards</a></p>
<p><span id="more-1226"></span></p>
<h2>Local Database</h2>
<p>The local database, as its name suggest, stores data about the local instance of Mongo, so if you have a 10 shard cluster, each individual node will have it&#8217;s own local database with its own data about itself. Although MongoDB uses this database to store information about itself, feel free to add your own collections to this database, if you have additional data which is specific to a single node.</p>
<p>Here&#8217;s a breakdown of collections that MongoDB with use by default:</p>
<h3>startup_log</h3>
<p>For each startup of Mongod, a document will be added to this collection with a bunch of useful data.</p>
<h3>me</h3>
<p>This collection contains an object id (_id), that represents the node. This object id is used when using shards and replication, so each nodes who who they must communicate with. If two nodes end up with the same object id, this collection can be dropped. it will be recreated and populated with a new object id a few seconds.</p>
<h3>slaves</h3>
<p>Returns a bunch of data about the slaves master.</p>
<h3>sources</h3>
<p>Contains all slaves which have ever been used as a sync source in replication. A sync source is essentially the master node where all data is pulled from. If a node changes it&#8217;s hostname, you may get errors about multiple hosts with the same object id (_id). To resolve this, drop this collection, it will be recreated and populated within a few seconds.</p>
<h3>oplog.rs</h3>
<p>This is the operations log, it stores all changed which have been pulled from the primary node, but still need to be executed on this node. This is a capped collection. I&#8217;ll  cover all the details about oplogs in an upcoming post on replication.</p>
<p class="edit"><span>Edit:</span> <a href="/mongodb-part-5-sharding/">Learn about MongoDB shards</a></p>
<h2>Config Database</h2>
<p>The config database is used to support sharding in MongoDB and should not be used by your application directly, unless for debugging purposes or setting configuration.</p>
<p>To understand this section fully, you really need to understand a lot of the factors behind how MongoDB shards work. This will all be covered in great depth in a separate post.</p>
<p class="edit"><span>Edit:</span> <a href="/mongodb-part-5-sharding/">Learn about MongoDB shards</a></p>
<h3>settings</h3>
<p>Each shard in MongoDB can have its own settings which are stored in this collection. Examples of setting of settings this collection will store includes, chunk size, balancer and chaining. I&#8217;ll explain all of these in my post on sharding.</p>
<h3>chunks</h3>
<p>Data on which chunks exist and on which shards. A chunk is essentially a collection of documents that all reside on the same node.</p>
<h3>shards</h3>
<p>Data on which shards exist and a list of their tags.</p>
<h3>tags</h3>
<p>Tags are used to make sure that certain documents are saved onto the correct shard. A common use case might be you have 10 shards using spinning disks and 1 with SSD&#8217;s and you want to make sure, all the most important data is saved to SSD, or speediness purposes. This could be accomplished by first adding a tag to a shard, then create tag ranges, which say where data should be saved. If a tag range is not found for a document, MongoDB will try to balance documents across shards fairly. This collection will store a list of all the tags and tag ranges.</p>
<h3>databases</h3>
<p>Data on which databases exist and what their primary shard is.</p>
<h3>collections</h3>
<p>Data on which shard collections exist.</p>
<h3>changelog</h3>
<p>Data on how data has moved between nodes and how they have split. Don&#8217;t worry about this to much for now. Just know MongoDB will sometimes move data between shards in an attempt to balance the load.</p>
<h3>locks</h3>
<p>Data about which balancing round is currently in progress. Balancing rounds are started by the mongos. Mongos is sort of like an entry point and router for your mongoDB cluster shards.</p>
<h2>Admin Database</h2>
<p>The admin database doesn&#8217;t store much and it doesn&#8217;t exist by default, it will be created once the first user has been created. I will show how to do this in a future article.</p>
<h3>system.users</h3>
<p>Stores information about each user. When using shards, users are stored on the config server. A root user should still be put onto each mongod for security reasons.</p>
<h2>System Collections</h2>
<p>The system collections are slightly different to what I&#8217;ve discussed previously. These collections are stored inside each of your application database. So say you create a database called blog. You might look for a collection called blog.system.indexes.</p>
<h3>system.indexes</h3>
<p>A list of all index in this database.</p>
<h3>system.profile</h3>
<p>if you execute <strong>db.setProfileLevel()</strong>, Mongod will start profiling the queries you deemed as slow to this collection.</p>
<h2>Conclusion</h2>
<p>Without the relevant knowledge on shards, that may have been a little tricky to follow at times. I&#8217;m you don&#8217;t have that knowledge, I cover it all in my post on <a href="/mongodb-part-5-sharding/">sharding</a>. But don&#8217;t worry about that too much for now. It&#8217;ll all come together naturally as the series progresses.</p>
<p>Next up I&#8217;ll be discussing MongoDB&#8217;s powerful indexing features. Thanks for reading.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-2-databases/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>NoSQL Essentials – Part 3 – Document databases</title>
		<link>https://www.jakowicz.com/nosql-essentials-part-3-document-databases/</link>
				<comments>https://www.jakowicz.com/nosql-essentials-part-3-document-databases/#respond</comments>
				<pubDate>Thu, 31 Jul 2014 17:54:43 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1047</guid>
				<description><![CDATA[This is post 3 of 6 in the series &#8220;NoSQL Essentials&#8221; Document databases are debatably the most talked about NoSQL database type at the time of writing. They’re easy to understand and really easy to work with. They offer all the benefits of using a key-value database (nearly), plus a lot more. Some of the... <a class="more-link" href="https://www.jakowicz.com/nosql-essentials-part-3-document-databases/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-nosql-essentials">
	<p class="wp-post-series-name">
		This is post 3 of 6 in the series <em>&ldquo;NoSQL Essentials&rdquo;</em>	</p>

	
	</aside>
<p><img src="/wp-content/uploads/2014/07/MongoDB.png" alt="Document Databases" class="size-full" /></p>
<h2>Document databases are debatably the most talked about NoSQL database type at the time of writing. They’re easy to understand and really easy to work with. They offer all the benefits of using a key-value database (nearly), plus a lot more. Some of the most popular key-value databases currently includes, MongoDB, CouchDB, Terrastore, OrientDB and RavenDB. In this article I am going to be focusing on MongoDB.</h2>
<p>Some people love Mongo, some people hate it, I’ve only played with it, but given it’s the most widely used NoSQL database and the most valued by employers. It’s certainly worth knowing a little about.</p>
<p><span id="more-1047"></span></p>
<h2>Differences from relational databases.</h2>
<ol>
<li>Relational databases contain tables, which in turn contain rows of data. Document databases contain collections and collections contain documents. Documents are stored in the form of JSON, well technically BSON (Binary JSON).</li>
<li>Document databases are aggregate oriented like key-value databases. This means that a document might contain a user record, with everything related to the user inside a single document e.g., recent history of a user; recent transactions; a list of friends. In a relational database these additional entities would be stored in separate tables and linked to via foreign keys.</li>
<li>Document databases are essentially key-values stores, but where the value part is fully examinable during reads. Meaning if you only wanted to find users which have a first name of Sammi, this would be possible. This is not possible in key-value stores.</li>
<li>In relational databases, each table has a schema which its rows must follow. In a MongoDB collection, each document does not have to follow a schema of any kind. It can store whatever it wants. New data can be added at any time, without changes to the collection being required. This provides the benefit, of not having an to store endless null values.</li>
</ol>
<h2>Naming conventions between MySQL and MongoDB</h2>
<table class="blog-table">
<tr>
<th>MySQL</th>
<th>MongoDB</th>
</tr>
<tr>
<td>Database Instance or MySQL instance</td>
<td>MongoDB instance</td>
</tr>
<tr>
<td>Database</td>
<td>Database</td>
</tr>
<tr>
<td>Table</td>
<td>Collection</td>
</tr>
<tr>
<td>Row</td>
<td>Document</td>
</tr>
<tr>
<td>Join</td>
<td>DBRef</td>
</tr>
</table>
<h2>Useful tips</h2>
<ol>
<li>One of the main goals of a document database, is to improve availability by replicating data across nodes.</li>
<li>MongoDB has a special field which it calls _id that is available in each document, this represents the document id. These id&#8217;s are automatically generated.</li>
<li>Each MongoDB instance can have multiple databases and each databases can have multiple collections.</li>
<li>When a document is created it must be set into a database and collection.</li>
<li>Your application does not need to know the state of which nodes are up and which are down, including the primary node. MongoDB can automatically elect a new primary if the old primary goes down. You can also set priorities on nodes, allowing nodes with the highest priority to take over as primary. This allows you to set your most beefy machines as primary.</li>
<li>When a failed primary node comes back online it automatically joins back to the cluster as a secondary, missing data will then be replicated to it.</li>
<li>When new nodes are added to a cluster, data will straight away start syncing to it, once the sync is complete, the node will be ready to serve read requests. This process does not require a restart of any nodes or result in any downtime.</li>
</ol>
<h2>Advantages</h2>
<ol>
<li>MongoDB conveniently provides a comprehensive solution to replication and read and write quorums.</li>
<li>Sharding of documents between nodes can easily be implemented for all document databases including MongoDB. Sharding is the number one option for scaling. You can think of sharding like partitioning in relational databases. If over time, new shards are created, the data will automatically move between shards to rebalance the load. One popular approach is to have different shards for different geographical locations.</li>
<li>The write quorum, takes a convention over configuration approach, where you can set the quorum for a particular database and then override this value on a specific collection or for just one specific write. You can also use keywords like “majority” to make sure at least 50% of nodes receive the write before a write it considered as successful. Inevitably, the more writes that are required, the more performance will suffer. This is known as the trade-off between consistency and latency. This process is known as WriteConcern.</li>
<li>In MongoDB you can set whether it’s acceptable to read from a secondary node by setting a slaveOk parameter. This can be set on the MongoDB instance, database, collection or on an individual document/operation. This allows you to only read from the primary where accuracy has to be 100% correct and read from secondaries when data is not required to be 100% up to date.</li>
<li>Materialised views can be created against document queries that require a lot of juice. These are similar to MySQL views.</li>
<li>MongoDB queries are far simpler to write than traditional relational database queries. This is because multiple entities are embedded inside a single document.</li>
<li>MongoDB clients are widely supported across all popular programming languages, including; PHP, JS, Python, Ruby, Java, C</li>
</ol>
<h2>Disadvantages</h2>
<ol>
<li>Just like key-value store, document databases do not support ACID transactions. There is also a document database called RavenDB which supports ACID transactions out the box. I’ve not tried this yet. However as I do I’ll post my findings.
</li>
</ol>
<h2>Use Cases</h2>
<ol>
<li>Real-time stats &#8211; Document internals can be updated at any time and materialised views can also be created and updated at any time. This gives great flexibility in keeping real-time stats up to date.</li>
<li>Gamification &#8211; A gamification system will allow rewards to be created from multiple implicit actions, this fits well with the schema-less model.</li>
<li>Event logging &#8211; Throughout an application you may have millions of different events, each with their only special values. It would be crazy to create a table in a relational database with hundred of columns to cater for all these scenarios. Most column would end up as null, in the past this data may be stored in a single meta data column as JSON or something similar. This does the job for writing, however it makes it impossible to execute read queries based on this data, at least without using extremely slow regex based searching. Schema-less documents to the rescue.</li>
<li>Content Management &#8211; Data inside content management system are usually easy to split into aggregates, due to there being a limited number of relationships. Allowing you to easy reap the benefits of a document database.</li>
</ol>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/nosql-essentials-part-3-document-databases/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
	</channel>
</rss>
