<?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>LearnMongo.com</title>
	<atom:link href="http://learnmongo.com/feed/rss2/" rel="self" type="application/rss+xml" />
	<link>http://learnmongo.com</link>
	<description>Resources for Learning and Mastering MongoDB</description>
	<lastBuildDate>Thu, 10 Nov 2011 07:19:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Mongo Seattle 2011</title>
		<link>http://learnmongo.com/posts/mongo-seattle-2011/</link>
		<comments>http://learnmongo.com/posts/mongo-seattle-2011/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 07:17:31 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Announcements]]></category>
		<category><![CDATA[MongoSeattle]]></category>

		<guid isPermaLink="false">http://learnmongo.com/?p=1143</guid>
		<description><![CDATA[TweetI&#8217;m happy to (sorta) announce I (Justin) will be giving a talk at Mongo Seattle 2011 on Dec 1st in downtown Seattle. According my contacts at 10Gen the registration is going gang-busters and there are going to be some really great sessions to attend including one from our buddy Damon Cortesi at Simply Measured as well as a bunch [...]]]></description>
			<content:encoded><![CDATA[<div id="tweetbutton1143" class="tw_button" style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http%3A%2F%2Flearnmongo.com%2Fposts%2Fmongo-seattle-2011%2F&amp;via=learnmongo&amp;text=Mongo%20Seattle%202011&amp;related=learnmongo:Learn+MongoDB&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Flearnmongo.com%2Fposts%2Fmongo-seattle-2011%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://learnmongo.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div><p>I&#8217;m happy to (sorta) announce I (Justin) will be giving a talk at <a href="http://www.10gen.com/events/mongo-seattle-2011">Mongo Seattle 2011</a> on Dec 1st in downtown Seattle.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-1144" title="MongoSeattle" src="http://learnmongo.com/wp-content/uploads/2011/11/MongoSeattle.png" alt="" width="485" height="220" /></p>
<p>According my contacts at 10Gen the registration is going gang-busters and there are going to be some really great sessions to attend including one from our buddy <a href="http://twitter.com/#!/dacort">Damon Cortesi</a> at <a href="http://simplymeasured.com/">Simply Measured</a> as well as a bunch of 10Gen engineers (the people that make MongoDB) plus MongoLab, Geek.net, VMWare and <a href="http://wordsquared.com/">WordSquared</a> (a super fun game!)</p>
<p>So, what are you waiting for?</p>
<p><strong>Go ahead a register <a href="http://www.10gen.com/events/mongo-seattle-2011" target="_blank">here</a></strong>  &#8230; and if you send me a DM or @Reply on Twitter (<a href="http://twitter.com/#!/learnmongo">@learnmongo</a>) I might just give you a pretty decent discount code!</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://learnmongo.com/posts/mongo-seattle-2011/feed/rss2/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Compacting MongoDB Collections</title>
		<link>http://learnmongo.com/posts/compacting-a-mongodb-collections/</link>
		<comments>http://learnmongo.com/posts/compacting-a-mongodb-collections/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 01:29:37 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Administration]]></category>

		<guid isPermaLink="false">http://learnmongo.com/?p=1126</guid>
		<description><![CDATA[TweetA while back we wrote a post explaining how to compact MongoDB data files, that example shows how to use some server side javascript and a cron job to automatically compact the data files on a schedule &#8230; however this isn&#8217;t always ideal as it will compact all the collections in a database at one [...]]]></description>
			<content:encoded><![CDATA[<div id="tweetbutton1126" class="tw_button" style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http%3A%2F%2Flearnmongo.com%2Fposts%2Fcompacting-a-mongodb-collections%2F&amp;via=learnmongo&amp;text=Compacting%20MongoDB%20Collections&amp;related=learnmongo:Learn+MongoDB&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Flearnmongo.com%2Fposts%2Fcompacting-a-mongodb-collections%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://learnmongo.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div><p>A while back we wrote a post explaining how to <a href="http://learnmongo.com/posts/compacting-mongodb-data-files/" target="_blank">compact MongoDB data files</a>, that example shows how to use some server side javascript and a cron job to automatically compact the data files on a schedule &#8230; however this isn&#8217;t always ideal as it will compact <em>all the collections in a database</em> at one time.</p>
<p>If you have a very large Collection you didn&#8217;t want to run the operation on &#8230;or a number of Collections in your database you didn&#8217;t wish to compact you were a bit out of luck.</p>
<p>Also, using <strong>repairDatabase()</strong> requires the disk space for the current database plus the repaired copy (i.e. <em>double the disk space.</em>)</p>
<p>Enter MongoDB 2.0 &#8230; in 2.0+ you can now use the simple <a href="http://www.mongodb.org/display/DOCS/compact+Command" target="_blank"><strong>compact</strong> command</a> to target the compact to a single collection.</p>
<p>Running compact has three major performance benefits:</p>
<ul>
<li>Compacts collection (less disk space.)</li>
<li>Defragments a collection (data pages are aligned better.)</li>
<li>Rebuilds and compacts the collection&#8217;s indexes (less RAM needed, and better perf.)</li>
</ul>
<p>If  you have a lot of read/write/delete operations going on in your Collection this could possibly have a fairly noticeable performance impact.</p>
<p>There are two ways to run the <strong>compact</strong> command:</p>
<pre>&gt; db.yourCollection.runCommand("compact");</pre>
<pre>&gt; db.runCommand({ compact : 'yourCollection' });</pre>
<p>Now, that said there are two big downsides to using compact &#8230;</p>
<ul>
<li>The compact command blocks operations on the collection until it&#8217;s done compacting (so it&#8217;s best to run this off hours during scheduled maintenance.)</li>
<li>It&#8217;s typically slower than repairDatabase in its actual operational time.</li>
</ul>
<p>Those aside, as part of routine maintenance compact is a really helpful new feature and might justify an upgrade to 2.0 all on it&#8217;s own!</p>
]]></content:encoded>
			<wfw:commentRss>http://learnmongo.com/posts/compacting-a-mongodb-collections/feed/rss2/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick Tip: How to $size up a MongoDB Array</title>
		<link>http://learnmongo.com/posts/quick-tip-how-to-size-up-a-mongodb-array/</link>
		<comments>http://learnmongo.com/posts/quick-tip-how-to-size-up-a-mongodb-array/#comments</comments>
		<pubDate>Fri, 05 Aug 2011 20:19:09 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Querying]]></category>
		<category><![CDATA[Quick Tip]]></category>

		<guid isPermaLink="false">http://learnmongo.com/?p=1115</guid>
		<description><![CDATA[TweetSince MongoDB will allow you to store more than just string and int values but also things like arrays &#8230; from time to time you might need to know how many items are in an array in your document. For example, say you have a hosting business and to make a good profit you need [...]]]></description>
			<content:encoded><![CDATA[<div id="tweetbutton1115" class="tw_button" style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http%3A%2F%2Flearnmongo.com%2Fposts%2Fquick-tip-how-to-size-up-a-mongodb-array%2F&amp;via=learnmongo&amp;text=Quick%20Tip%3A%20How%20to%20%24size%20up%20a%20MongoDB%20Array&amp;related=learnmongo:Learn+MongoDB&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Flearnmongo.com%2Fposts%2Fquick-tip-how-to-size-up-a-mongodb-array%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://learnmongo.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div><p>Since MongoDB will allow you to store more than just <strong>string</strong> and <strong>int</strong> values but also things like <strong>arrays</strong> &#8230; from time to time you might need to know how many items are in an array in your document.</p>
<p>For example, say you have a hosting business and to make a good profit you need to sell at least three upgrades to each hosting client.</p>
<p>To make sure you market to the correct people you want to find all the clients with two upgrades (and get them to sign up for just one more.)</p>
<p>Your general document structure looks something like this:</p>
<pre>{
 customer_name : "Sam Taylor",
 email : "sam@widgetxyz.com",
 upgrades: ["ssl", "diskspace 3", "RAM 5"]
}</pre>
<pre>{
 customer_name : "Kyle Lopez",
 email : "klopez@buymybikes.com",
 upgrades: ["diskspace 3", "RAM 5"]
}</pre>
<p>To get all the clients that have two upgrades we&#8217;ll use the <a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24size" target="_blank">$size</a> operator:</p>
<pre>&gt; db.clients.find( { upgrades : { $size: 2 } } );</pre>
<p>Now you&#8217;ll get back all the documents that have two upgrades in the &#8220;upgrades&#8221; array (or in this example, the document for &#8220;Kyle Lopez&#8221;.)</p>
<p><strong>What about a range?</strong></p>
<p><em>Unfortunately the $size operator doesn&#8217;t support ranges (like getting all documents with 2 to 4 array values.) To do that you&#8217;d need to create your own separate field to keep track of the count and query on that field.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://learnmongo.com/posts/quick-tip-how-to-size-up-a-mongodb-array/feed/rss2/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick Tip: Copy DBs Between Servers</title>
		<link>http://learnmongo.com/posts/quick-tip-copy-dbs-between-servers/</link>
		<comments>http://learnmongo.com/posts/quick-tip-copy-dbs-between-servers/#comments</comments>
		<pubDate>Mon, 11 Apr 2011 09:26:49 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[Quick Tip]]></category>

		<guid isPermaLink="false">http://learnmongo.com/?p=1096</guid>
		<description><![CDATA[TweetInspired by this Stackoverflow question I thought it would be worth while to post this quick tip &#8230; If you ever need to copy (or &#8220;clone&#8221;) a MongoDB databse between two MongoDB servers its as easy as running the copyDatabase() command. First, change into your admin db &#8230; Then, run copyDatabase() supplying the needed information, the [...]]]></description>
			<content:encoded><![CDATA[<div id="tweetbutton1096" class="tw_button" style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http%3A%2F%2Flearnmongo.com%2Fposts%2Fquick-tip-copy-dbs-between-servers%2F&amp;via=learnmongo&amp;text=Quick%20Tip%3A%20Copy%20DBs%20Between%20Servers&amp;related=learnmongo:Learn+MongoDB&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Flearnmongo.com%2Fposts%2Fquick-tip-copy-dbs-between-servers%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://learnmongo.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div><p>Inspired by this Stackoverflow <a href="http://stackoverflow.com/questions/5495137/how-do-i-copy-a-database-from-one-mongodb-server-to-another/5495401#5495401" target="_blank">question</a> I thought it would be worth while to post this quick tip &#8230;</p>
<p><img class="size-thumbnail wp-image-1103 alignright" title="340x_ifezvozhtxc" src="http://learnmongo.com/wp-content/uploads/2011/04/340x_ifezvozhtxc-150x150.jpg" alt="" width="150" height="150" /></p>
<p>If you ever need to <a href="http://www.mongodb.org/display/DOCS/Clone+Database" target="_blank">copy</a> (or &#8220;clone&#8221;) a MongoDB databse <em>between</em> two MongoDB servers its as easy as running the <strong>copyDatabase()</strong> command.</p>
<p>First, change into your admin db &#8230;</p>
<p>Then, run <strong>copyDatabase()</strong> supplying the needed information, the &#8220;from_db&#8221; (the database to copy) the &#8220;to_db&#8221; and the host name of the database you are copying &#8230;</p>
<blockquote><p>&gt; use admin;<br />
&gt; db.copyDatabase(&#8230;);</p></blockquote>
<p>You&#8217;ll need to run the <strong>copyDatabase()</strong> command on the sever you want to &#8220;copy&#8221; the database <em>to</em>, aka the &#8220;destantion&#8221; server &#8230;</p>
<blockquote>
<pre><code>&gt; db.copyDatabase(from_db, to_db, from_host);</code></pre>
</blockquote>
<p>If you are running MongoDB with accounts/password <a href="http://www.mongodb.org/display/DOCS/Security+and+Authentication#SecurityandAuthentication-MongoSecurity" target="_blank">via <strong>&#8211;auth</strong></a> you&#8217;ll need to add that info on there too &#8230;</p>
<blockquote>
<pre><code>&gt; db.copyDatabase(from_db, to_db, from_host, username, password);</code></pre>
</blockquote>
<p>A simple example for a database named &#8220;weyoun&#8221; on a host called &#8220;delta.quad.com&#8221; would be like so &#8230;</p>
<blockquote>
<pre><code>&gt; db.copyDatabase('weyoun', 'weyoun', 'delta.quad.com');</code></pre>
</blockquote>
<p>There ya go, you should be good to go copying your MongoDB database!</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://learnmongo.com/posts/quick-tip-copy-dbs-between-servers/feed/rss2/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Sorry It Has Been So Quiet &#8230;</title>
		<link>http://learnmongo.com/posts/sorry-it-has-been-so-quiet/</link>
		<comments>http://learnmongo.com/posts/sorry-it-has-been-so-quiet/#comments</comments>
		<pubDate>Wed, 23 Feb 2011 07:11:56 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Announcements]]></category>

		<guid isPermaLink="false">http://learnmongo.com/?p=1077</guid>
		<description><![CDATA[TweetDear Readers, Sorry it&#8217;s been so quiet lately &#8230; thing is LearnMongo is moving! Well not moving sites or anything &#8230; but I&#8217;m moving &#8230; to the sunny North West (at least that&#8217;s what my new boss keeps telling me?) &#8230; Seattle Bound (wait that sounds wrong) Once all the moving stuff is taken care of LearnMongo [...]]]></description>
			<content:encoded><![CDATA[<div id="tweetbutton1077" class="tw_button" style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http%3A%2F%2Flearnmongo.com%2Fposts%2Fsorry-it-has-been-so-quiet%2F&amp;via=learnmongo&amp;text=Sorry%20It%20Has%20Been%20So%20Quiet%20%26%238230%3B&amp;related=learnmongo:Learn+MongoDB&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Flearnmongo.com%2Fposts%2Fsorry-it-has-been-so-quiet%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://learnmongo.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div><p>Dear Readers,</p>
<p>Sorry it&#8217;s been so quiet lately &#8230; thing is LearnMongo is moving!<a href="http://learnmongo.com/wp-content/uploads/2011/02/seattle.jpg"><img class="alignright size-medium wp-image-1079" title="seattle" src="http://learnmongo.com/wp-content/uploads/2011/02/seattle-300x200.jpg" alt="" width="180" height="120" /></a></p>
<p>Well not moving sites or anything &#8230; but <em>I&#8217;m moving</em> &#8230; to the sunny North West (<em>at least that&#8217;s what my new boss keeps telling me</em>?) &#8230;</p>
<h2>Seattle Bound (wait that sounds wrong)</h2>
<p><img class="alignleft size-thumbnail wp-image-1080" title="seattle-rain-1" src="http://learnmongo.com/wp-content/uploads/2011/02/seattle-rain-1-150x150.jpg" alt="" width="150" height="150" /></p>
<p>Once all the moving stuff is taken care of LearnMongo will be back to regular posts (staring in March.)</p>
<p>I&#8217;m sure I&#8217;ll have plenty of coffee to fuel some awesome Mongoness.</p>
<p>Thanks for your support so far, and I&#8217;m looking forward to lots more Mongo in 2011.</p>
<p>~ Justin</p>
]]></content:encoded>
			<wfw:commentRss>http://learnmongo.com/posts/sorry-it-has-been-so-quiet/feed/rss2/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>MongoLA 2011 Talk Slides</title>
		<link>http://learnmongo.com/posts/mongola-2011-talk-slides/</link>
		<comments>http://learnmongo.com/posts/mongola-2011-talk-slides/#comments</comments>
		<pubDate>Tue, 18 Jan 2011 06:23:14 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[MongoLA]]></category>

		<guid isPermaLink="false">http://learnmongo.com/?p=1048</guid>
		<description><![CDATA[Tweet MongoLA 2011 Here are the slides from my talk at MongoLA last week, hopefully the audio will be up soon (I will post it here.) There is a nice write up of the event here&#8230; thanks to everyone that came! Beyond Logging Using MongoDB to Power a Private Social Network (Oh, and log millions [...]]]></description>
			<content:encoded><![CDATA[<div id="tweetbutton1048" class="tw_button" style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http%3A%2F%2Flearnmongo.com%2Fposts%2Fmongola-2011-talk-slides%2F&amp;via=learnmongo&amp;text=MongoLA%202011%20Talk%20Slides&amp;related=learnmongo:Learn+MongoDB&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Flearnmongo.com%2Fposts%2Fmongola-2011-talk-slides%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://learnmongo.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div><p><img src="http://learnmongo.com/wp-content/uploads/2011/01/mongoLA_badge_blank.png" style="border: 0px;"></p>
<h2>MongoLA 2011</h2>
<p>Here are the slides from my talk at MongoLA last week, hopefully the audio will be up soon (I will post it here.)</p>
<p>There is a nice write up of the event <a href="http://pydanny.blogspot.com/2011/01/january-mongo-la-conference.html">here</a>&#8230; thanks to everyone that came! </p>
<blockquote><h2>Beyond Logging<br />
<h2>
<h3><a title="Beyond Logging: Using MongoDB to Power a Private Social Network (Oh, and log millions of e-mails too.)" href="http://www.slideshare.net/justinjenkins/beyond-logging-using-mongodb-to-power-a-private-social-network-oh-and-log-millions-of-emails-too">Using MongoDB to Power a Private Social Network</a></h3>
<p><i>(Oh, and log millions of e-mails too.)</i></p></blockquote>
<blockquote><p><center>
<div id="__ss_6608230" style="width: 425px;"><object id="__sse6608230" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="355" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="src" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=prezomongodbprivatesocialnetworkupload-110118000942-phpapp02&amp;stripped_title=beyond-logging-using-mongodb-to-power-a-private-social-network-oh-and-log-millions-of-emails-too&amp;userName=justinjenkins" /><param name="name" value="__sse6608230" /><param name="allowfullscreen" value="true" /><embed id="__sse6608230" type="application/x-shockwave-flash" width="425" height="355" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=prezomongodbprivatesocialnetworkupload-110118000942-phpapp02&amp;stripped_title=beyond-logging-using-mongodb-to-power-a-private-social-network-oh-and-log-millions-of-emails-too&amp;userName=justinjenkins" name="__sse6608230" allowscriptaccess="always" allowfullscreen="true"></embed></object></div>
<div>
</div>
<p></center></p></blockquote>
<p><img height="269" width="640" alt="photo" src="http://farm6.static.flickr.com/5241/5354924305_1d0ae16a29_z.jpg"><br />
<a href="http://www.flickr.com/photos/mediatemplerocks/5354924409/in/set-72157625824169878/"><img height="341" width="640" alt="photo" src="http://farm6.static.flickr.com/5124/5354924409_23719770c4_z.jpg"></a><br />
<img height="427" width="640" alt="photo" src="http://farm6.static.flickr.com/5123/5355539912_ea8e3c8641_z.jpg"><br />
<img height="427" width="640" alt="photo" src="http://farm6.static.flickr.com/5048/5355540030_d859e54f19_z.jpg"></p>
]]></content:encoded>
			<wfw:commentRss>http://learnmongo.com/posts/mongola-2011-talk-slides/feed/rss2/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Compacting MongoDB Data Files</title>
		<link>http://learnmongo.com/posts/compacting-mongodb-data-files/</link>
		<comments>http://learnmongo.com/posts/compacting-mongodb-data-files/#comments</comments>
		<pubDate>Sun, 02 Jan 2011 05:45:45 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[Stackoverflow]]></category>

		<guid isPermaLink="false">http://learnmongo.com/?p=968</guid>
		<description><![CDATA[Tweet StackOverflow Anwser Series This is a new &#8220;concept&#8221; post based on StackOverflow Questions/Answers. Feel free to comment below if this format is helpful &#38; informative! Overview This Answer covers the following MongoDB topics: Data Files Compacting Data Files The db.repairDatabase(); command Capped Collections Server-side Javascript Question StackOverflow Link Is there a way to auto compact MongoDB [...]]]></description>
			<content:encoded><![CDATA[<div id="tweetbutton968" class="tw_button" style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http%3A%2F%2Flearnmongo.com%2Fposts%2Fcompacting-mongodb-data-files%2F&amp;via=learnmongo&amp;text=Compacting%20MongoDB%20Data%20Files&amp;related=learnmongo:Learn+MongoDB&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Flearnmongo.com%2Fposts%2Fcompacting-mongodb-data-files%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://learnmongo.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div><p><img style="border: 0px;" src="http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png" alt="" /></p>
<h3>StackOverflow Anwser Series</h3>
<blockquote><p>This is a new &#8220;concept&#8221; post based on StackOverflow Questions/Answers.</p>
<p><em>Feel free to comment below if this format is helpful &amp; informative!</em></p></blockquote>
<h2>Overview</h2>
<p>This <strong><em>Answer </em></strong>covers the following MongoDB topics:</p>
<ul>
<li>Data Files</li>
<li>Compacting Data Files</li>
<li>The db.repairDatabase(); command</li>
<li>Capped Collections</li>
<li>Server-side Javascript</li>
</ul>
<h2>Question</h2>
<p><a href="http://stackoverflow.com/q/4555938/296167" target="_blank">StackOverflow Link</a></p>
<h3><span style="color: #0000ff;"><strong><em><span style="color: #993300;">Is there a way to auto compact MongoDB Data Files?</span></em></strong></span></h3>
<p>The mongodb <a href="http://www.mongodb.org/display/DOCS/Excessive+Disk+Space" target="_blank">documentation says</a> that:</p>
<blockquote><p>To compact this space, run db.repairDatabase() from the mongo shell (note this operation will block and is slow).</p></blockquote>
<p>I&#8217;m wondering how to make the mongodb free deleted disk space <strong>automatically</strong>?</p>
<h2>Answer</h2>
<p><a href="http://stackoverflow.com/questions/4555938/auto-compact-the-deleted-space-in-mongodb/4560096#4560096" target="_blank">StackOverflow Link</a></p>
<p>In general if you don&#8217;t need to shrink your datafiles you shouldn&#8217;t shrink them at all. This is because &#8220;growing&#8221; your datafiles on disk is a fairly expensive operation and the more space that MongoDB can allocate in datafiles the less fragmentation you will have.</p>
<p><em><strong>Also doing any sort of &#8220;shrink&#8221; will likely be a rather expensive operation and will likely lock your database while it&#8217;s running!</strong></em></p>
<p>So, you should try avoid shrinking and provide as much disk-space as possible for the database.</p>
<p><em>However</em> if you must shrink the database you should keep two things in mind.</p>
<ul>
<li>MongoDB grows it&#8217;s data files by doubling so the datafiles may be 64MB, then 128MB, etc up to 2GB (at which point it stops doubling to keep files until 2GB.)</li>
<li>As with most any database &#8230; to do operations like shrinking you&#8217;ll need to schedule a separate job to do so, there is no &#8220;autoshrink&#8221; in MongoDB. <em>In fact of the major noSQL databases (hate that name) only Riak will autoshrink. </em>So, you&#8217;ll need to create a job using your OS&#8217;s scheduler to run a shrink. You could use an bash script, or have a job run a php script, etc.</li>
</ul>
<p><strong>Server-side Javascript</strong></p>
<p>You can use <a href="http://www.mongodb.org/display/DOCS/Server-side+Code+Execution" target="_blank">server-side Javascript</a> to do the shrink and run that JS via mongo&#8217;s shell on a regular bases via a job (like cron or the windows scheduling service) &#8230;</p>
<p>Assuming a collection called <strong>foo</strong> you would save the javascript below into a file called <strong>bar.js</strong> and run &#8230;</p>
<pre><code>$ mongo foo bar.js
</code></pre>
<p>The javascript file would look something like &#8230;</p>
<p><strong>bar.js</strong></p>
<pre><code>// Get a the current collection size.
var storage = db.foo.storageSize();
var total = db.foo.totalSize();

print('Storage Size: ' + tojson(storage));

print('TotalSize: ' + tojson(total));

print('-----------------------');
print('Running db.repairDatabase()');
print('-----------------------');

// Run repair
db.repairDatabase()

// Get new collection sizes.
var storage_a = db.foo.storageSize();
var total_a = db.foo.totalSize();

print('Storage Size: ' + tojson(storage_a));
print('TotalSize: ' + tojson(total_a));
</code></pre>
<p>This will run and return something like &#8230;</p>
<pre><code>MongoDB shell version: 1.6.4
connecting to: foo
Storage Size: 51351
TotalSize: 79152
-----------------------
Running db.repairDatabase()
-----------------------
Storage Size: 40960
TotalSize: 65153
</code></pre>
<p>Run this on a schedule (during non-peak hours) and you are good to go.</p>
<p><strong>Capped Collections</strong></p>
<p>However there is one other option, <a rel="nofollow" href="http://www.mongodb.org/display/DOCS/Capped+Collections">capped collections</a>.</p>
<blockquote><p>Capped collections are fixed sized collections that have a very high performance auto-FIFO age-out feature (age out is based on insertion order). They are a bit like the &#8220;RRD&#8221; concept if you are familiar with that.</p>
<p>In addition, capped collections automatically, with high performance, maintain insertion order for the objects in the collection; this is very powerful for certain use cases such as logging.</p></blockquote>
<p>Basically you can limit the size of (or number of documents in ) a collection to say .. 20GB and once that limit is reached MongoDB will start to throw out the oldest records and replace them with newer entries as they come in.</p>
<p>This is a great way to keep a large amount of data, discarding the older data as time goes by and keeping the same amount of disk-space used.</p>
]]></content:encoded>
			<wfw:commentRss>http://learnmongo.com/posts/compacting-mongodb-data-files/feed/rss2/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Quick Tip: Using Users in MongoDB</title>
		<link>http://learnmongo.com/posts/quick-tip-mongodb-users/</link>
		<comments>http://learnmongo.com/posts/quick-tip-mongodb-users/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 08:33:32 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[Quick Tip]]></category>

		<guid isPermaLink="false">http://learnmongo.com/?p=938</guid>
		<description><![CDATA[TweetBy default a MongoDB install does not use a username/password combination to access the database. No Password, But Why? This is down to the design philosophy of MongoDB which is to push much of the &#8220;logic&#8221; to the application level and keep the database doing what databases do best! Hence,  given the way that MongoDB [...]]]></description>
			<content:encoded><![CDATA[<div id="tweetbutton938" class="tw_button" style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http%3A%2F%2Flearnmongo.com%2Fposts%2Fquick-tip-mongodb-users%2F&amp;via=learnmongo&amp;text=Quick%20Tip%3A%20Using%20Users%20in%20MongoDB&amp;related=learnmongo:Learn+MongoDB&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Flearnmongo.com%2Fposts%2Fquick-tip-mongodb-users%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://learnmongo.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div><p>By default a MongoDB install does not use a username/password combination to access the database.</p>
<p><img class="size-full wp-image-940 alignright" title="ComputerSafeCartoon" src="http://learnmongo.com/wp-content/uploads/2010/12/ComputerSafeCartoon.jpg" alt="" width="210" height="215" /></p>
<h2>No Password, But Why?</h2>
<p>This is down to the <em>design philosophy</em> of MongoDB which is to push much of the &#8220;logic&#8221; to the application level and keep the database doing what databases do best! Hence,  given the way that MongoDB is normally used it&#8217;s generally not necessary.</p>
<p>In a SQL environment you might have multiple users with multiple groups and schemas to lock down different levels of the database, tables, views, stored procedures, etc. &#8230;</p>
<p>The idea of this is of course to 1) protect data from unauthorized modification or deletion as well as 2)  limiting the <em>tug &#8216;o war</em> between users by clearly defining their rights.</p>
<p>So, you can give the accounting department different privileges then the marketing department or given root access to the developers (of course.)</p>
<p>Conversely MongoDB&#8217;s design philosophy would pass these (generally) over to the application itself to handle.</p>
<h2>I Don&#8217;t Care, I Still Want Passwords!</h2>
<p><img class="alignright size-full wp-image-953" title="speakeasy-themeprop-l" src="http://learnmongo.com/wp-content/uploads/2010/12/speakeasy-themeprop-l.jpg" alt="" width="184" height="123" /></p>
<p>No worries, if the idea of no users/passwords keeps you up at nights you can still have them!</p>
<p>MongoDB (currently) supports users on the database level with both &#8220;read/write&#8221; and &#8220;read only&#8221; options.</p>
<p>You can see all the users in a database in the <strong>system.users</strong> collection &#8230;</p>
<pre>&gt; use mydatabase
&gt; db.system.users.find()</pre>
<h2>Creating MongoDB Users</h2>
<p>To adding a new user is fairly straight forward &#8230;</p>
<h3>Read/Write User</h3>
<pre>$ ./mongo
&gt; use mydatabase
&gt; db.addUser("admin", "Sup3rG00dP@azzword")</pre>
<p>This creates a read/write user for the database <strong>mydatabase</strong> (you can choose any username you wish.)</p>
<p>This user will be &#8220;good for&#8221; this database alone.</p>
<h3>Read Only User</h3>
<pre>&gt; db.addUser("web", "prettyGoodPass", true)</pre>
<p>The &#8220;true&#8221; parameter there makes the user read only (great for parts of the application code that you want to make sure never accidentally preform a write operation.)</p>
<h3>Using A User: Authenticate</h3>
<p>To &#8220;login&#8221; as a user you&#8217;ll need to <em>authenticate</em>, simply use &#8230;</p>
<pre>&gt; db.auth("admin", "Sup3rG00dP@azzword")</pre>
<p>You can also authenticate via the command line using the <strong>mongo</strong> parameters below &#8230;</p>
<pre>  -u [ --username ] arg username for authentication
  -p [ --password ] arg password for authentication</pre>
<h3>Changing Passwords</h3>
<p>To change the password simply run the addUser command again with a new password.</p>
<pre>&gt; db.addUser("web", "wayGooderPass", true)</pre>
<h3>Delete a User</h3>
<p>To remove a user you need to remove the corresponding document for that user in the <strong>system.users</strong> collection.</p>
<pre>&gt; db.system.users.remove({"user" : "web"});</pre>
<h2>Set MongoDB to Force Authentication</h2>
<p><img class="size-full wp-image-954 alignleft" title="Beefeater" src="http://learnmongo.com/wp-content/uploads/2010/12/Beefeater.jpg" alt="" width="134" height="324" /></p>
<p>To force MongoDB to use authentication you&#8217;ll need to add the <strong>&#8211;auth</strong> parameter to MongoDB at startup (so you would need to restart.)</p>
<p>If you are using an unauthorized user you&#8217;ll get an error something like &#8230;</p>
<p><strong>error: { &#8220;$err&#8221; : &#8220;unauthorized for db [mydatabase] lock type: -1 &#8221; }</strong></p>
<p>If you have a read only user and attempt a write option you&#8217;ll simply get back &#8230;</p>
<p><strong>unauthorized</strong></p>
<p>Lastly, if you try to use a user that doesn&#8217;t have read/write privlages on the <strong>admin </strong>database &#8230;</p>
<p>So, if you try to do something like list the avaible database on the server ( &gt; show dbs ) you&#8217;ll get error too and you&#8217;ll need to make sure you switch to an account with read/write privlages in <strong>admin</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://learnmongo.com/posts/quick-tip-mongodb-users/feed/rss2/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MongoSV Pics</title>
		<link>http://learnmongo.com/posts/mongosv-pics/</link>
		<comments>http://learnmongo.com/posts/mongosv-pics/#comments</comments>
		<pubDate>Tue, 07 Dec 2010 07:58:55 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[MongoSV]]></category>

		<guid isPermaLink="false">http://learnmongo.com/?p=923</guid>
		<description><![CDATA[TweetReally enjoyed MongoSV this last week &#8230; a few posts (in process) inspired by it! In the meantime here are some pics, the first few are by yours truly. (Note: I&#8217;m no photographer! Ha.) Click here to view these pictures larger]]></description>
			<content:encoded><![CDATA[<div id="tweetbutton923" class="tw_button" style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http%3A%2F%2Flearnmongo.com%2Fposts%2Fmongosv-pics%2F&amp;via=learnmongo&amp;text=MongoSV%20Pics&amp;related=learnmongo:Learn+MongoDB&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Flearnmongo.com%2Fposts%2Fmongosv-pics%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://learnmongo.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div><p>Really enjoyed MongoSV this last week &#8230; a few posts (in process) inspired by it!</p>
<p>In the meantime here are some pics, the first few are by yours truly.</p>
<p>(Note: I&#8217;m no photographer! Ha.)</p>
<p><object id="Slideshow" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="625" height="425" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="name" value="Slideshow" /><param name="align" value="middle" /><param name="flashvars" value="configurl=http%3A%2F%2Fcmd.shutterfly.com%2Fcommands%2Fpictures%2Fgetshareoutslideshowconfig%3Fsite%3Dmongodb%26page%3Dmongodb%2Fpictures%26node%3D15" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.shutterfly.com/flashapps/flashslideshow/Slideshow.swf" /><param name="bgcolor" value="#869ca7" /><param name="allowfullscreen" value="true" /><param name="quality" value="high" /><embed id="Slideshow" type="application/x-shockwave-flash" width="625" height="425" src="http://www.shutterfly.com/flashapps/flashslideshow/Slideshow.swf" quality="high" allowfullscreen="true" bgcolor="#869ca7" allowscriptaccess="always" flashvars="configurl=http%3A%2F%2Fcmd.shutterfly.com%2Fcommands%2Fpictures%2Fgetshareoutslideshowconfig%3Fsite%3Dmongodb%26page%3Dmongodb%2Fpictures%26node%3D15" align="middle" name="Slideshow"></embed></object></p>
<p style="width: 625px; margin-top: 0; text-align: center;"><a href="http://mongodb.shutterfly.com/pictures/15?eid=116">Click here to view these pictures larger</a><img src="https://os.shutterfly.com/b/ss/sflyshareprod/1/H.15/111?pageName=sharekey&amp;c1=pictures&amp;c2=embed" border="0" alt="" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://learnmongo.com/posts/mongosv-pics/feed/rss2/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started With MongoDB GridFS</title>
		<link>http://learnmongo.com/posts/getting-started-with-mongodb-gridfs/</link>
		<comments>http://learnmongo.com/posts/getting-started-with-mongodb-gridfs/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 03:11:16 +0000</pubDate>
		<dc:creator>Justin</dc:creator>
				<category><![CDATA[GridFS]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://learnmongo.com/?p=802</guid>
		<description><![CDATA[TweetOne really useful built-in feature of MongoDB is it&#8217;s GridFS. This filesystem within MongoDB was designed for &#8230; well, holding files, especially files over 4MB &#8230; why 4MB? Well BSON objects are limited to 4MB in size (BSON is the format that MongoDB uses to store it&#8217;s database information) so GridFS helps store files across [...]]]></description>
			<content:encoded><![CDATA[<div id="tweetbutton802" class="tw_button" style="float: right; margin-left: 10px;"><a href="http://twitter.com/share?url=http%3A%2F%2Flearnmongo.com%2Fposts%2Fgetting-started-with-mongodb-gridfs%2F&amp;via=learnmongo&amp;text=Getting%20Started%20With%20MongoDB%20GridFS&amp;related=learnmongo:Learn+MongoDB&amp;lang=en&amp;count=horizontal&amp;counturl=http%3A%2F%2Flearnmongo.com%2Fposts%2Fgetting-started-with-mongodb-gridfs%2F" class="twitter-share-button"  style="width:55px;height:22px;background:transparent url('http://learnmongo.com/wp-content/plugins/wp-tweet-button/tweetn.png') no-repeat  0 0;text-align:left;text-indent:-9999px;display:block;">Tweet</a></div><p>One really useful built-in feature of MongoDB is it&#8217;s GridFS.</p>
<p><img class="alignleft" src="http://learnmongo.com/wp-content/uploads/2010/11/tholian-web.jpg" alt="" width="173" height="130" />This filesystem within MongoDB was designed for &#8230; well, holding files, especially files over 4MB &#8230; why  4MB?</p>
<p>Well BSON objects are limited to 4MB in size (BSON is the format that MongoDB uses to store it&#8217;s database information) so GridFS helps store files across multiple chunks.</p>
<p>As Kristina Chodorow of 10Gen <a href="http://www.snailinaturtleneck.com/blog/2010/02/11/mongo-mailbag-2-updating-gridfs-files/" target="_blank">puts it</a> &#8230;</p>
<blockquote><p>GridFS breaks large files into manageable chunks. It saves the chunks to one collection (fs.chunks) and then metadata about the file to another collection (fs.files). When you query for the file, GridFS queries the chunks collection and returns the file one piece at a time.</p></blockquote>
<p>Why would you want to break large files in to &#8220;chunks&#8221;? A lot of of comes down to efficient memory &amp; disk usage.</p>
<h2>Chunks &#8216;O Random-Access Memory<span style="font-weight: normal; font-size: 13px;"><img class="alignright" src="http://learnmongo.com/wp-content/uploads/2010/11/chunk-truffle-249x3001.jpg" alt="" width="149" height="180" /></span></h2>
<p><em><span style="color: #888888;">Gee, mister. You&#8217;re even hungrier than I am.</span></em></p>
<p>Say you want to store larger files (maybe a 2GB video) when you preform a query on that file all 2GB needs to be loaded into memory &#8230; say you have a bigger file, 10GB, 25GB etc &#8230; it&#8217;s quite likely you&#8217;d run out of usable RAM or not have that much RAM available at all!</p>
<p>So, GridFS solves this problem by streaming the data back (in chunks) to the client &#8230; this way you&#8217;d never need to use more than 4MB of RAM.</p>
<h3>Other Reasons to Use GridFS</h3>
<p>Some other nicities of GridFS are &#8230;</p>
<ul>
<li>If you are using replication or autosharding your GridFS files will be seamlessly sharded or replicated for you.</li>
<li>Since MongoDB datafiles are broken into 2 GB chunks MongoDB will automatically break your files into OS manageable pieces.</li>
<li>You won&#8217;t have to worry about OS limitations like &#8216;weird&#8217; filenames or a large number of files in one directory, etc.</li>
<li>MongoDB will auto generate the MD5 hash of your file and store it in the file&#8217;s document. This is useful to compare the stored file with it&#8217;s MD5 hash to see if it was uploaded correctly, or already exists your database.</li>
</ul>
<h2>Command Line: mongofiles</h2>
<p>An easy way to get started and see how GridFS works is the use the <strong><span style="color: #666699;">mongofiles</span></strong> command line utility (if you downloaded the binaries of MongoDB you should file this tool in the <strong><span style="color: #666699;">bin</span></strong> directory.)</p>
<p>To make things easy, <strong><span style="color: #666699;">mongofiles</span></strong> accepts RESTful looking commands, for example &#8230;</p>
<pre>$ <strong><span style="color: #800000;">./mongofiles -d myfiles put 03-smbd-menu-screen.mp3</span></strong>
connected to: 127.0.0.1

added file: {
   _id: ObjectId('4ce9ddcb45d74ecaa7f5a029'),
   filename: "03-smbd-menu-screen.mp3",
   chunkSize: 262144,
   uploadDate: new Date(1290395084166),
   md5: "7872291d4e67ae8b8bf7aea489ab52c1",
   length: 1419631 }

done!</pre>
<p>This uploaded (PUT) the <strong><span style="color: #666699;">03-smbd-menu-screen.mp3</span></strong> file to a database called <strong><span style="color: #666699;">myfiles</span></strong> (it could be any database.)</p>
<p>This file now resides in the <strong><span style="color: #666699;">myfiles</span></strong> DB in the <strong><span style="color: #666699;">fs.files</span></strong><span style="color: #666699;"> </span>Collection. We can confirm this by passing the <strong><span style="color: #666699;">list</span></strong> command.</p>
<pre>$ <strong><span style="color: #800000;">./mongofiles -d myfiles list</span></strong>
connected to: 127.0.0.1
03-smbd-menu-screen.mp3 1419631</pre>
<p>Hurrah! We have our files in there &#8230;you can also query it via the MongoDB Shell like so &#8230;</p>
<pre>&gt; use myfiles;
&gt; <strong><span style="color: #800000;">db.fs.files.find({});</span></strong>
{
   "_id" : ObjectId("4ce9ddcb45d74ecaa7f5a029"),
   "filename" : "03-smbd-menu-screen.mp3",
   "chunkSize" : 262144,
   "uploadDate" : "Mon Nov 22 2010 03:04:44 GMT+0000 (UTC)",
   "md5" : "7872291d4e67ae8b8bf7aea489ab52c1",
   "length" : 1419631
}</pre>
<p>Note: the size, upload date &amp; md5 are all produced for you which is pretty  handy.</p>
<h2>Uploading a File (or Data) via MongoDB Driver</h2>
<p><img class="alignleft size-full wp-image-826" title="data-goonies" src="http://learnmongo.com/wp-content/uploads/2010/11/data-goonies.jpg" alt="" width="216" height="142" />Likely a more realistic way of storing files in GridFS will be via one of the many available language drivers. Each driver handles GridFS a little differantly but the concepts are the same.</p>
<p>The first thing you need to sort is out is are you going to upload actual <em>files</em> or are you going to create files from <em>strings of data</em>?</p>
<p>For example an application that allows a user to upload a video directly from their computer to your application would use the <em>file</em> method &#8230; however an application that would take a profile image (for example) and compress and resize it for use in your application would likely use the <em>string of data</em> method.</p>
<h3>The File Method</h3>
<p>In this example we&#8217;ll assume the file is already in your filesystem in the <strong><span style="color: #666699;">/tmp/</span></strong> dir, but the file could be wherever your web-server/PHP is configured to access.</p>
<p>To work with GridFS files in PHP you use <a href="http://us.php.net/manual/en/class.mongogridfs.php" target="_blank">MongoGridFS</a> class, more information can be found in the documentation.</p>
<p>We will use <strong><span style="color: #666699;">MongoGridFS::storeFile</span></strong> but you could also use <strong><span style="color: #666699;">MongoGridFS::put</span></strong> (which works like the command line example.)</p>
<pre>&lt;?php

<span style="color: #888888;">// Connect to Mongo and set DB and Collection</span>
$mongo = new Mongo();
$db = $mongo-&gt;myfiles;

<span style="color: #888888;">// GridFS</span>
$grid = $db-&gt;getGridFS();

<span style="color: #888888;">// The file's location in the File System</span>
<div id="_mcePaste">$path = "/tmp/";</div>
<div id="_mcePaste">$filename = "03-smbd-menu-screen.mp3";</div>
<div id="_mcePaste"><span style="color: #888888;">// Note metadata field &amp; filename field</span>
$storedfile = $grid-&gt;<strong><span style="color: #800000;">storeFile</span></strong>($path . $filename,
                 array("metadata" =&gt; array("filename" =&gt; $filename),
                 "filename" =&gt; $filename));</div>

<span style="color: #888888;">// Return newly stored file's Document ID</span>
echo $storedfile;

?&gt;</pre>
<h3>The String of Data Method</h3>
<p>String of data is very similar only we&#8217;ll pass a string instead of a file/path so use the code above but use <strong><span style="color: #666699;">storeBytes</span></strong> instead.</p>
<pre>$storedfile = $grid-&gt;<strong><span style="color: #800000;">storeBytes</span></strong>("This is test file data!",
                 array("metadata" =&gt; array("filename" =&gt; $filename),
                 "filename" =&gt; $filename));</pre>
<p>You could of course pass any string, string representation of a images (or an encoded file via a string) where we&#8217;ve put &#8220;This is test file data!&#8221; &#8230;</p>
<h3>A Little About Metadata</h3>
<p>For PHP it doesn&#8217;t really matter but since other drivers handle things slightly differently it&#8217;s best to write any metadata to it&#8217;s own <strong><span style="color: #666699;">metadata</span></strong> field as well as a separate filename field as we have done in the example above.</p>
<p>You can put any file metadata that makes sense for your use in the <strong><span style="color: #666699;">metadata</span></strong> field.</p>
<h2>Stream Back Files</h2>
<p>Now that our file or files are loaded into GridFS streaming back the file is farily simple &#8230;</p>
<p><img class="alignright" src="http://learnmongo.com/wp-content/uploads/2010/11/chunk-screaming.jpg" alt="" width="115" height="154" /></p>
<ul>
<li>Connect to MongoDB</li>
<li>Do a findOne() on the file</li>
<li>Load it into memory using <span style="font-family: Consolas, Monaco, 'Courier New', Courier, monospace; line-height: 18px; font-size: 12px; white-space: pre;"><strong><span style="color: #800000;">getBytes</span></strong>()</span></li>
<li>Set the proper headers</li>
<li>Stream the file back to the browser</li>
</ul>
<p>So, here is how we&#8217;d stream back an image in PHP &#8230;</p>
<h3>Stream an Image from GridFS to the Browser</h3>
<p><em>Warning: this will load the file into memory. If the file is bigger than your memory, this will cause problems!</em></p>
<pre>&lt;?php
<span style="color: #888888;">// Connect to Mongo and set DB and Collection</span>
$mongo = new Mongo();
$db = $mongo-&gt;myfiles;     

<span style="color: #888888;">// GridFS</span>
$gridFS = $db-&gt;getGridFS();     

<span style="color: #888888;">// Find image to stream</span>
$image = $gridFS-&gt;findOne("chunk-screaming.jpg");

<span style="color: #888888;">// Stream image to browser</span>
header('Content-type: image/jpeg');
echo $image-&gt;<strong><span style="color: #800000;">getBytes</span></strong>();

?&gt;</pre>
<p>With a little adjustment you could stream back an mp3, or video, or prompt for a file download, etc.</p>
<h3>Other Ways to Search for GridFD Files</h3>
<p>You could also use the Document&#8217;s ID &#8230;</p>
<pre>$image = $gridFS-&gt;findOne(
         <span style="color: #800000;"><strong>array("_id" =&gt; new MongoId("4ceb167810f1d50a80e1c71c")</strong></span>)
         );</pre>
<p>That will likely be how your application would look up a file in a real world system.</p>
<p>You can use any valid MongoDB <strong><span style="color: #666699;">findOne()</span></strong> query in it&#8217;s place as well, or use <span style="color: #000080;"><strong><span style="color: #666699;">find()</span></strong></span> to get back a GridFS <em>cursor</em> of files, you can find out more about that <a href="http://www.php.net/manual/en/class.mongogridfscursor.php" target="_blank">here</a>.</p>
<h2>Deleting Files</h2>
<p>You delete files in the same way, there are actually a couple ways to remove GridFS files, but we&#8217;ll just use one of the easiest &#8230;</p>
<p><em>Be really careful about passing the correct query to remove or you might just find yourself removing all your files! You can also use </em><a href="http://www.php.net/manual/en/mongogridfs.delete.php" target="_blank"><em>MongoGridFS::delete</em></a><em> and pass the Document&#8217;s ID only.</em></p>
<pre>&lt;?php

<span style="color: #888888;">// Connect to Mongo and set DB and Collection</span>
$mongo = new Mongo();
$db = $mongo-&gt;myfiles;

<span style="color: #888888;">// GridFS</span>
$gridFS = $db-&gt;getGridFS();

<span style="color: #888888;">// Find file to remove </span>
$removeFile = $gridFS-&gt;<span style="color: #800000;"><strong>remove</strong></span><span style="color: #800000;"><span style="color: #000000;">(
                array("_id" =&gt; new MongoId("</span></span><span style="color: #800000;"><span style="color: #000000;">4ceb167810f1d50a80e1c71c</span></span><span style="color: #800000;"><span style="color: #000000;">"))</span></span>
              );

?&gt;</pre>
<h2>Wrap Up</h2>
<p>Hopefully you can now get started with GridFS and see if it will work well for your application &#8230; remember if you stream back (using the image example above) the files they will be loaded into memory and not streamed in 4MB chunks &#8230;so be careful!</p>
<p>Have fun.</p>
]]></content:encoded>
			<wfw:commentRss>http://learnmongo.com/posts/getting-started-with-mongodb-gridfs/feed/rss2/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  learnmongo.com/feed/rss2/ ) in 0.68277 seconds, on May 19th, 2012 at 12:08 am UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 19th, 2012 at 1:08 am UTC -->
