<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>FredZvt.WriteLines();</title>
	<atom:link href="http://fredzvt.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://fredzvt.wordpress.com</link>
	<description></description>
	<lastBuildDate>Thu, 03 Mar 2011 14:27:49 +0000</lastBuildDate>
	<language>pt-br</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='fredzvt.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>FredZvt.WriteLines();</title>
		<link>http://fredzvt.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://fredzvt.wordpress.com/osd.xml" title="FredZvt.WriteLines();" />
	<atom:link rel='hub' href='http://fredzvt.wordpress.com/?pushpress=hub'/>
		<item>
		<title>No-SQL – MongoDB – From introduction to high level usage in C# with NoRM.</title>
		<link>http://fredzvt.wordpress.com/2010/04/24/no-sql-mongodb-from-introduction-to-high-level-usage-in-csharp-with-norm/</link>
		<comments>http://fredzvt.wordpress.com/2010/04/24/no-sql-mongodb-from-introduction-to-high-level-usage-in-csharp-with-norm/#comments</comments>
		<pubDate>Sat, 24 Apr 2010 19:26:38 +0000</pubDate>
		<dc:creator>fredzvt</dc:creator>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[No-SQL]]></category>
		<category><![CDATA[NoRM]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[couchdb]]></category>
		<category><![CDATA[databases]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[mongodb-csharp]]></category>

		<guid isPermaLink="false">http://fredzvt.wordpress.com/?p=194</guid>
		<description><![CDATA[Learn a little about the No-SQL moviment, the MongoDB database and how to use it in your C# projects using the mongodb-csharp driver and the NoRM library.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fredzvt.wordpress.com&amp;blog=12849895&amp;post=194&amp;subd=fredzvt&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div style="background-color:#F0F0F0;margin-bottom:10px;">
Clique <a href="http://fredzvt.wordpress.com/2010/04/10/no-sql-mongodb-da-introducao-a-utilizacao-em-alto-nivel-em-csharp-com-norm/">aqui</a> para ler a versão original desse artigo em português.
</div>
<p>First I would like to apologize in advance for my bad English. This is a translation of my <a href="http://fredzvt.wordpress.com/2010/04/10/no-sql-mongodb-da-introducao-a-utilizacao-em-alto-nivel-em-csharp-com-norm/">original article in Portuguese</a>. I will be grateful for any corrections.</p>
<p>In this article I&#8217;ll try to make an introduction to the No-SQL movement, the document oriented database MongoDB and three ways to use it: via shell, via the C# driver mongodb-csharp and via the NoRM library.</p>
<p>The objective of this article is that the reader becomes aware of what is and the basics of how to use MongoDB. For that, the examples that we will cover are intentionally simple and does not seek to explore the various ways to perform an operation on MongoDB either to demonstrate it&#8217;s full capacity.</p>
<p><span id="more-194"></span></p>
<p>Please keep in mind that I&#8217;m still studying the software and still do not have practical experience in projects using MongoDB, with my limited knowledge of my private studies, and although I&#8217;ve made every effort, using reliable sources, to ensure the veracity of informations until the time of this writing and tested on my computer all the code examples cited here, I can not give full guarantees. Constructive criticism and corrections are extremely welcome.</p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">Contents</h2>
<ul>
<li><a href="#no-sql">No-SQL</a>
<ul>
<li><a href="#no-sql-or-relational">No-SQL or relational databases!? Both!</a></li>
</ul>
</li>
<li>
    <a href="#mongodb">MongoDB</a></p>
<ul>
<li><a href="#mongodb-vs-couchdb">MongoDB vs CouchDB</a></li>
<li><a href="#mongodb-installation">Installation and initialization of MongoDB server</a></li>
</ul>
</li>
<li><a href="#mongo-shell">Using MongoDB with Mongo shell</a></li>
<li><a href="#mongodb-csharp">Using MongoDB with mongodb-csharp</a></li>
<li><a href="#NoRM">Using MongoDB with NoRM</a></li>
<li><a href="#Updates">Updates after the publication of this article</a></li>
</ul>
<p><a name="no-sql"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">No-SQL</h2>
<p>Today there are several databases that break with the requirements met by traditional relational database management systems and these are their main characteristics:</p>
<div style="background-color:#eee;padding:5px;">
<p><img class="alignright size-thumbnail wp-image-36" title="Not only SQL" style="border:none;" src="http://fredzvt.files.wordpress.com/2010/04/nosql.png?w=150&#038;h=88" alt="" width="150" height="88" /></p>
<ul>
<li>The disuse of SQL as the query API. (Examples of APIs used include JSON, BSON, REST, RPC, etc.).</li>
<li>Does not guarantee atomic operations (non-ACID).</li>
<li>Distributed and horizontally scalable.</li>
<li>Abandonment to predefined schemas.</li>
<li>Non-tabular data storing (eg: key-value, object, graphs, etc.).</li>
</ul>
<p style="font-size:smaller;margin-bottom:0;line-height:100%;padding:5px 15px;">Note: Not all databases categorized as No-SQL possess all these characteristics, some have one, others another, some all.</p>
</div>
<p style="margin-top:18px;">The effort of development and evangelization community of these new technological approaches was named No-SQL and have been doing a lot of noise since early 2009. No-SQL should be understood as &#8220;Not only SQL&#8221; although this interpretation is not very obvious. In my opinion, it would make more sense if it had been labeled No-Relational.</p>
<p>The most complete listing of databases that can be framed as part of the No-SQL that I found is in <a href="http://nosql-database.org/" target="_blank">http://nosql-database.org/</a>. When I wrote this article, there were 47 databases distributed among different categories.</p>
<p>There is a nice introduction (in Portuguese) to No-SQL databases from the point of view of scalability in blog <a href="http://escalabilidade.com/2010/03/08/introducao-ao-nosql-parte-i/" target="_blank">Escalabilidade</a>.</p>
<p>Here I focus on <strong>MongoDB</strong> who, along with CouchDB, interested me the most since I started researching the subject.</p>
<p><a name="no-sql-or-relational"></a></p>
<h3>No-SQL or relational databases!? Both!</h3>
<p>Note that non-relational databases do not represent a complete substitution from relational databases. Ideally you must know the pros and cons of each approach and use the most adequate to your needs in the scenarios that we encounter.</p>
<p>I believe that the most obvious scenario that can be target of criticism is the scenario of reports generation. This cases are excellently resolved giving the best use of relational databases and Data Warehouse systems doing frequent aggregations of production data stored in non-relational databases.</p>
<p><a href="http://blog.wekeroad.com/2010/02/05/reporting-in-nosql" target="_blank">Rob Conery</a> wrote an excellent article about this topic.</p>
<p><a name="mongodb"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">MongoDB</h2>
<p><a href="http://www.mongodb.org/" target="_blank">MongoDB</a> is a schemaless, document oriented, high performance, scalable database that tries to give the best of key-value stores, where documents are stored as <a href="http://www.json.org/" target="_blank">JSON</a> structured documents, and relational database management systems with features like many indexing models and dynamic queries.</p>
<p>His name comes from &#8220;humongous&#8221; (something giant), perhaps with a sarcastic tone to be such a tiny piece of software and so powerful or perhaps because it can scale up to become something really monstrous. Who knows&#8230;</p>
<p>Today is used in production for at least 40 sites of high performance and access, including sites like <em><a href="http://sourceforge.net/" target="_blank">SourceForge</a></em>, <em><a href="http://github.com/" target="_blank">GitHub</a></em>, <em><a href="http://www.ea.com/" target="_blank">EA</a></em> and <em><a href="http://www.nytimes.com/" target="_blank">The New York Times</a></em>.</p>
<p><a name="mongodb-vs-couchdb"></a></p>
<h3>MongoDB vs CouchDB</h3>
<p>Although <a href="http://www.mongodb.org/" target="_blank">MongoDB</a> and <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> <a href="http://www.mongodb.org/display/DOCS/Comparing+Mongo+DB+and+Couch+DB" target="_blank">have differences</a> in their implementation approaches in aspects such as versioning and concurrency control, scalability, query API, etc, and although both are open source projects, I still consider them as competitors by offering similar features. I believe MongoDB has a great advantage and will develop more quickly because it is written in C++ and not in <a href="http://www.erlang.org/index.html" target="_blank">Erlang</a>, like CouchDB.</p>
<p><a name="mongodb-installation"></a></p>
<h3>Installation and initialization of MongoDB server</h3>
<p>MongoDB can be downloaded in compiled versions for Linux, OS X and Windows. For the examples in this article I use version 1.4.0 compiled for Windows 64-bit but I believe that there are no differences using the 32-bit version.</p>
<p><img src="http://fredzvt.files.wordpress.com/2010/04/mongodb_folders.jpg?w=168&#038;h=156" alt="" title="MongoDB Folders" width="168" height="156" style="float:right;border:none;margin:5px;padding:5px;" />When you finish downloading the zip file, unzip it into any folder on your computer. Four directories will be created: bin, include, lib and lib64. The folders include, lib and lib64 are used for those who will use MongoDB with C++, in our case what matters is the application mongod.exe inside the bin folder, which is the server of MongoDB.</p>
<p>By default, MongoDB uses the c:\data\db as default path to their databases files <strong>but this folder is not automatically created</strong>, so <strong>create them before running the server</strong>. If you prefer to use another folder to store your databases files, boot the server with the parameter <span style="background-color:#111111;color:#EEEEEE;"><code>&ndash;&ndash;dbpath [path]</code></span>. I personally like to also use the parameter <span style="background-color:#111111;color:#EEEEEE;"><code>&ndash;&ndash;directoryperdb</code></span> that causes MongoDB create a subfolder for each database that is created. Finally, running mongod.exe the server will initialize by default on localhost, port 27017.</p>
<div id="attachment_79" class="wp-caption alignnone" style="width: 687px"><a href="http://fredzvt.files.wordpress.com/2010/04/mongod_iniciado.jpg"><img src="http://fredzvt.files.wordpress.com/2010/04/mongod_iniciado.jpg?w=700" alt="" title="mongod_iniciado"   class="size-full wp-image-79" /></a><p class="wp-caption-text">Console with mongod.exe started and waiting for connections.</p></div>
<p>Next we&#8217;ll perform the four basic operations for manipulating data (CRUD) and simple queries on a test base in MongoDB using Mongo shell, in C# with driver <a href="http://github.com/samus/mongodb-csharp" target="_blank">mongodb-csharp</a> and with the high-level library <a href="http://wiki.github.com/atheken/NoRM/" target="_blank">NoRM</a>.</p>
<p><a name="mongo-shell"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">Using MongoDB with Mongo shell</h2>
<p>The executable mongo.exe is the mongo shell. Run it without parameters and it&#8217;ll be initialized connected to the server in its default port (27017).</p>
<p>Enter the command <span style="background-color:#111111;color:#EEEEEE;"><code>show dbs</code></span> and Mongo will list all databases that exist. By default there is <em>admin</em>, <em>local</em> and <em>test</em>. To change the database that will receive our commands, use the command <span style="background-color:#111111;color:#EEEEEE;"><code>use [database name]</code></span>. The creation of new databases occurs automatically when we add some data to a database that doesn&#8217;t exists.</p>
<p>We&#8217;ll now insert our first document in our new base, effectively creating it. Enter the command <span style="background-color:#111111;color:#EEEEEE;"><code>use mybase</code></span>, this will inform the shell that we will send commands to the database <em>mybase</em>, even if it not exists yet. At this time the base does not exist, you can confirm this executing the command <span style="background-color:#111111;color:#EEEEEE;"><code>show dbs</code></span> again. Now we&#8217;ll use the command <span style="background-color:#111111;color:#EEEEEE;"><code>db.[collection name].save( [JSON document] )</code></span> to create and save a new document, note that the document should be written using JavaScript Object Notation (<a href="http://www.json.org/" target="_blank">JSON</a>). Enter the command: <span style="background-color:#111111;color:#EEEEEE;"><code>db.People.save({ name: "Fred", age: 28 })</code></span> and now the command <span style="background-color:#111111;color:#EEEEEE;"><code>db.People.save({ name: "Carlos", age: 30 })</code></span>. Okay, now we have a base named <em>mybase</em> with a collection named <em>People</em> and two JSON documents in this collection: one representing a person named Fred with 28 years old and one representing a person named Carlos with 30 years old.</p>
<p>There are two additional limitations on JSON documents written to be stored by MongoDB: the names of the keys can not start with $ or have . (dots) in any place. Thus, documents such as { $test : 1 } or { &#8220;test.key&#8221; : &#8220;value&#8221; } will be invalid.</p>
<p>One of the most interesting features of some No-SQL document oriented databases (including Mongo) is the disuse of predefined schemas in documents of the same collection. In other words, a collection can have documents whose structures are completely different. For those who are familiar with relational databases where each document (record) structure (columns) is restricted by the table that contains it, this is a huge paradigm shift. To illustrate this, let&#8217;s add a new document in our collection that is not structured as the previous two that we include. Enter the command <span style="background-color:#111111;color:#EEEEEE;"><code>db.People.save({ firstname: "Joaquim", lastname:"Silva", age: "15 years old" })</code></span>. With this command we just insert a document in the collection <em>People</em> with a structure completely different from previous documents and this is absolutely valid.</p>
<p>Now that we have data stored, its time to do some queries on them. In shell, the queries are primarily conducted by the command <span style="background-color:#111111;color:#EEEEEE;"><code>db.[collection name].find(...)</code></span>. If we execute this command without any parameters it will list all documents of a collection, so <span style="background-color:#111111;color:#EEEEEE;"><code>db.People.find()</code></span> will return the three documents that we just inserted. The <em>find</em> command can be used in many ways, allowing us to run any queries that we imagine in our collections. This is a feature that makes MongoDB stand out amongst other No-SQL databases. To exemplify a little (very little indeed!) this feature, we&#8217;ll run a query with a simple criterion: to return only the document that represents the person named Fred we would run the command <span style="background-color:#111111;color:#EEEEEE;"><code>db.People.find({ name: "Fred" })</code></span>. The <em>find</em> command is one of many that uses a JSON document as criteria specification to ensure that Mongo will apply the desired effect just in the documents that met this criteria.</p>
<p>Note that the returned document has a property beyond that stated explicitly: the _id property. Every document stored in MongoDB collection has to have a unique _id property. We can declare it explicitly in the creation of the document or MongoDB will automatically create an ObjectID typed property called _id for us. This property is the primary identifier of a document in MongoDB and will be indexed by default in all collections. The identifier property has no obligation to be of type ObjectID and may be of any type supported by JSON documents (<a href="http://www.mongodb.org/display/DOCS/BSON">BSON</a> actually), but the use type ObjectID is recommended to facilitate the scalability of MongoDB databases.</p>
<p>To delete a document in a collection, we will use the command <span style="background-color:#111111;color:#EEEEEE;"><code>db.[collection name].remove([criteria JSON document])</code></span>, therefore, to remove the document that represents the person named Carlos, we would perform <span style="background-color:#111111;color:#EEEEEE;"><code>db.People.remove({ name: "Carlos" })</code></span>.</p>
<p>To update a document of the collection, we need to get the desired document first, modify it and save it back to the database, effectively updating it. The shell provides us a very useful command when you need to get a single document from a collection to handle it: the command <span style="background-color:#111111;color:#EEEEEE;"><code>db.[collection name].findOne([criteria JSON document])</code></span>, so, by running the command <span style="background-color:#111111;color:#EEEEEE;"><code>joaquim = db.People.findOne({ firstname: "Joaquim" });</code></span> we will assign to the variable <em>joaquim</em> the document returned by the database. Now we can change it and save it again in the collection: run <span style="background-color:#111111;color:#EEEEEE;"><code>joaquim.lastname = "Souza";</code></span> to change his last name and <span style="background-color:#111111;color:#EEEEEE;"><code>db.People.save(joaquim);</code></span> to update the document in the database.</p>
<p>In my opinion, the shell is the main administration interface to MongoDB, although its main use is through a programming language specific driver. All the features of MongoDB can be accessed from the shell, becoming intimate to this tool will greatly assist you to work with MongoDB databases. See the <a href="http://www.mongodb.org/display/DOCS/mongo+-+The+Interactive+Shell">documentation for the shell</a> on the official MongoDB.</p>
<p><a name="mongodb-csharp"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">Using MongoDB with mongodb-csharp</h2>
<p>As shell is the interface between human-MongoDB the <a href="http://www.mongodb.org/display/DOCS/Drivers">programming language specific drivers</a> are the interfaces between software-MongoDB. Today there are drivers for 25 programming languages. Only for .NET framework, there are 6 drivers/tools according to <a href="http://deserialized.com/about/">Bryan Migliorisi</a> in <a href="http://deserialized.com/the-state-of-mongodb-and-csharp/">an article on his blog</a>, and among these the <a href="http://github.com/samus/mongodb-csharp#readme">MongoDB-csharp</a> driver, developed by a troupe led by <a href="http://twitter.com/samcorder">Sam Corder</a>, is the most mature to date.</p>
<p><img src="http://fredzvt.files.wordpress.com/2010/04/github_mongodb-csharp.png?w=700" alt="" title="mongodb-csharp @ github"   class="alignleft size-full wp-image-118" style="border:none;" />A small criticism to the project goes to the poor documentation, I think at least the wiki project should contain some examples of the major features but it is possible to understand how it works analyzing the test projects. I believe this will be greatly improved with some time as the project is still very young.</p>
<p>In this article we will use the <a href="http://github.com/samus/mongodb-csharp/downloads">version 0.82.2 of MongoDB-csharp</a> to run our examples. Its API is very similar to the shell, making our lives even easier.</p>
<p>Unpacking the download file, we&#8217;ll have three libraries: <code>MongoDB.Driver.dll</code>, <code>MongoDB.GridFS.dll</code> and <code>MongoDB.Linq.dll</code>. The one which we must add as a reference in our project is the <code>MongoDB.Driver.dll</code>. The other two are, respectively, an API to support the <a href="http://www.mongodb.org/display/DOCS/GridFS" target="_blank">GridFS</a> specification, which allows storage of binary objects over 4MB in MongoDB and basic support for LINQ.</p>
<p>The first thing we must do in our code to use MongoDB is connect to server:</p>
<p><pre class="brush: csharp;">
using MongoDB.Driver;

Mongo mongo = new Mongo();
mongo.Connect();
</pre></p>
<p>Then we get a reference to the database and the collection that we want to handle:</p>
<p><pre class="brush: csharp;">
Database db = mongo.GetDatabase(&quot;mybase&quot;);
IMongoCollection collection = db.GetCollection(&quot;People&quot;);
</pre></p>
<p>The class <code>MongoDB.Driver.Document</code> represents a MongoDB document and works much like a <code>System.Collections.Generic.Dictionary&lt;String, Object&gt;</code>:</p>
<p><pre class="brush: csharp;">
Document doc = new Document();
doc.Add(&quot;name&quot;, &quot;Guilherme&quot;);
doc.Add(&quot;age&quot;, 22);
</pre></p>
<p>To persist a the new document in the referenced collection:</p>
<p><pre class="brush: csharp;">
collection.Save(doc);
</pre></p>
<p>When we run the <em>find</em> command in shell, what we get in return is actually a <a href="http://www.mongodb.org/display/DOCS/Queries+and+Cursors" target="_blank">cursor</a> that is automatically iterated by shell but we could assign it to a variable and manipulate it manually. MongoDB-csharp uses the same principle, but here the work of iterating over the values will always be manual.</p>
<p><pre class="brush: csharp;">
ICursor cur = collection.FindAll();
foreach (Document iDoc in cur.Documents)
{
    Console.WriteLine(&quot;Name: {0}, Age: {1}&quot;, iDoc[&quot;name&quot;], iDoc[&quot;age&quot;]);
}
</pre></p>
<p>To update a document, the process is, again, similar to run on shell: get a reference to a specific document, modify it and save it back to the collection:</p>
<p><pre class="brush: csharp;">
Document doc2 = collection.FindOne(new Document() {{&quot;firstname&quot;, &quot;Joaquim&quot;}});
doc2[&quot;lastname&quot;] = &quot;Silva&quot;;

collection.Save(doc2);
</pre></p>
<p>And, finally, to delete a document:</p>
<p><pre class="brush: csharp;">
collection.Delete(doc2);
collection.Delete(new Document() {{ &quot;name&quot;, &quot;Guilherme&quot; }});
</pre></p>
<p>Could it be more simple? The driver MongoDB-csharp provides APIs for almost all the features of MongoDB and is very easy to use, as we saw.</p>
<p><a name="NoRM"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">Using MongoDB with NoRM</h2>
<p><img src="http://fredzvt.files.wordpress.com/2010/04/norm_logo.png?w=700" alt="" title="NoRM logo"   class="alignright size-full wp-image-144" style="border:none;" />After met the <a href="http://wiki.github.com/atheken/NoRM/" target="_blank">NoRM library</a>, when I use MongoDB-csharp to access a database I get a bitter taste of low-level in my mouth, I remember the time when I use <code>Recordsets</code> to access databases in classic ASP.</p>
<p>The NoRM library provides a strongly typed, high level abstraction for manipulating documents in MongoDB as well as a friendly API to send commands to the server.</p>
<p>NoRM, as well as MongoDB-csharp, is an open-source project hosted on <a href="http://github.com/" target="_blank">github</a>, has <a href="http://andrewtheken.com/" target="_blank">Andrew Theken</a> as leader and primary developer and contributors of the weight of <a href="" target="_blank">Rob Conery</a> (the mind behind the project <a href="http://www.subsonicproject.com/" target="_blank">SubSonic</a>). It&#8217;s a project so young that even has a release yet, but already attracting <u>lots</u> of attention!</p>
<p><img src="http://fredzvt.files.wordpress.com/2010/04/github_download_source.png?w=700" alt="" title="Download Source"   class="alignleft size-full wp-image-147" style="border:none;" /></p>
<p>Because there are no releases so far, we have to download the code to compile on our machine. In the <a href="http://wiki.github.com/atheken/NoRM/" target="_blank">github&#8217;s project page</a>, click the &#8220;Download Source&#8221; and then select the compression format of your preference. Save and unpack it in any folder on your computer. Or make a clone of the Git repository. Open the solution <code>NoRM.sln</code>, compile the NoRM project and add reference to the generated DLL into your application or add the project <code>NoRM/NoRM.csproj</code> to your solution and reference the project in your application.</p>
<p>The library works in a strongly typed manner, automatic translating your C# classes in BSON documents to store in MongoDB and vice versa, so let&#8217;s create the class <code>Person</code>:</p>
<p><pre class="brush: csharp;">
class Person
{
    public ObjectId ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
</pre></p>
<p>NoRM imposes certain conventions in our classes to run serialization/deserialization without problems, they are:</p>
<ul>
<li>The supported types for serialization/deserialization (until the moment of this writing) are:
<ul>
<li><code>int</code></li>
<li><code>bool</code></li>
<li><code>double</code></li>
<li><code>float</code>
<ul>
<li>Will be always serialized/deserialized as <code>double</code></li>
</ul>
</li>
<li><code>DateTime</code></li>
<li><code>string</code></li>
<li><code>byte[]</code></li>
<li><code>Norm.ObjectId</code></li>
<li><code>Regex</code></li>
<li><code>Guid</code></li>
<li><code>Enums</code>
<ul>
<li>Must inherit from <code>uint</code>, <code>int</code>, <code>ulong</code>, <code>long</code></li>
<p> (eg: <code>public enum meu_enum : int {...}</code>)</ul>
</li>
<li><code>Norm.ScopedCode</code></li>
<li><code>IEnumerable&lt;T&gt;</code>
<ul>
<li>T must be of one of these supported types as well.</li>
<li><span style="text-decoration:line-through;">Will be always deserialized as List&lt;T&gt;</li>
<p></span> <strong>Update:</strong> As Andrew Theken inform: It seems that now other types of collections are supported.</ul>
</li>
</ul>
</li>
<li>Its recomended that, when use value types, we should use use use their nullable versions because when the document been deserialized hasn&#8217;t a property of your C# class, this will be assigned to <code>null</code>. (Eg: use <code>int?<code> instead of <code>int</code>)</li>
<li>Every C# class must possess a public property called <code>_id</code> or <code>ID</code>, being of one of the supported types, but if we use <code>Guid</code> or <code>Norm.ObjectId</code> it initialization will be automatic.
<ul>
<li>If we want to use another property as our identifier we could use the <code>[MongoIdentifier]</code> attribute, getting rid of the requirement to create the property <code>_id</code> or <code>ID</code>.</li>
</ul>
</li>
<li><span style="text-decoration:line-through;">All public properties must have public getter and setter.</span> <strong>Update:</strong> As Andrew Theken inform Karl Seguin’s work has made private/protected getters/setters available.</li>
<li>NoRM still don't recognizes ciclic references, leaving for us clients to take care of this. Be warned, if this occurs it will generate an inifinite loop in runtime.</li>
<li>NoRM still don't recognizes if you try to deserialize a value in an invalid property type. (Eg: A type convertion error will occur if you try to deserialize a BSON integer value in a <code>Datetime</code> property.</li>
<li>The size of a document cannot be greater than 4MB. (In fact, this is a limitation of MongoDB, not of NoRM. If you must store a binary greater than 4MB, use GridFS specification)</li>
<li>The precision of <code>DateTime</code> type is in milliseconds. If you need more precision, use <code>doubles</code> instead.</li>
</ul>
<p>I know that at first glance seems to have many restrictions but, in my opinion, for a project that has his first commit in January 30 of 2010, its quite an achievement. Remember that this library is open source and if you miss a feature that was not implemented you could submit a patch. Besides, all I need to implement my domain entities in plain <a href="http://en.wikipedia.org/wiki/Plain_Old_CLR_Object" target="_blank">POCOs</a> are being offered at the library.</p>
<p>With everything in place, lets open a connection with MongoDB server an get a reference to our collection:</p>
<p><pre class="brush: csharp;">
using Norm;
using Norm.Collections;

Mongo mongo = new Mongo(&quot;mybase&quot;);
MongoCollection&lt;Person&gt; Collection = mongo.GetCollection&lt;Person&gt;(&quot;People&quot;);
</pre></p>
<p>To insert a new person in our collection we just need to create an instance of Person and save it in our collection:</p>
<p><pre class="brush: csharp;">
Person Bruno = new Person();
Bruno.Name = &quot;Bruno&quot;;
Bruno.Age = 35;

Collection.Save(Bruno);
</pre></p>
<p>To update a document, we first get the document from the collection but this time in a strongly typed way. To specify the criteria we'll use a anonymous type with only a property called <code>Name</code>. Then we'll update our instance of Person and save it back to the collection:</p>
<p><pre class="brush: csharp;">
Person Bruno2Update = Collection.FindOne(new { Name = &quot;Bruno&quot; });
Bruno2Update.Age = 40;
Bruno2Update.Name = &quot;Bruno Garcia&quot;;

Collection.Save(Bruno2Update);
</pre></p>
<p>For beautifully list the persons in the collection:</p>
<p><pre class="brush: csharp;">
IEnumerable&lt;Person&gt; People = Collection.Find();
foreach (Person p in People)
{
    Console.WriteLine(&quot;Name: {0}, Age: {1}&quot;, p.Name, p.Age);
}
</pre></p>
<p>And, finally, could not be simpler to delete a person from the collection:</p>
<p><pre class="brush: csharp;">
Collection.Delete(Bruno2Update);
</pre></p>
<p><a name="Updates"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">Updates after the publication of this article</h2>
<p>The wide acceptance of this article was a big surprise for me and I would like to thank everyone who gave me some kind of feedback.</p>
<p>I would add some notes and corrections sent in by readers:</p>
<p>First of all, I want to clarify that in this article I'm not really giving preference to the driver mongodb-csharp nor the NoRM library. For me, it was clear that the two libraries are proposed to different things. While mongodb-csharp undertakes to provide the API in a manner more similar to the shell, giving us greater flexibility, NoRM proposed to provide greater productivity more distant to shell approach and closer to the reality of developers, providing a direct mapping of their classes in C# so strongly typed, however less flexible.</p>
<p>I was happy to be informed by Craig Wilson that soon we'll have a release of mongodb-csharp that brings feature parity with NoRM plus a little extra.</p>
<p>If the project mongodb-csharp is now proposed to offer all the features offered by NoRM project and vice versa, at first I will give preference to mongodb-csharp since I consider it a more mature project. But in that case, I don't understand why the two teams did not come together to develop a unique library, taking the best of the two worlds.</p>
<p>Finally, I inform you that there may be updates in the article body in order to better inform the readers with the informations that I receive. Where there is a fix, I'll strike through text and do inline comment.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/fredzvt.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/fredzvt.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/fredzvt.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/fredzvt.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/fredzvt.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/fredzvt.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/fredzvt.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/fredzvt.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/fredzvt.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/fredzvt.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/fredzvt.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/fredzvt.wordpress.com/194/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/fredzvt.wordpress.com/194/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/fredzvt.wordpress.com/194/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fredzvt.wordpress.com&amp;blog=12849895&amp;post=194&amp;subd=fredzvt&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://fredzvt.wordpress.com/2010/04/24/no-sql-mongodb-from-introduction-to-high-level-usage-in-csharp-with-norm/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/ee38139ed3fc8836d92c270c0dd83f74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mimiefred</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/nosql.png?w=150" medium="image">
			<media:title type="html">Not only SQL</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/mongodb_folders.jpg" medium="image">
			<media:title type="html">MongoDB Folders</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/mongod_iniciado.jpg" medium="image">
			<media:title type="html">mongod_iniciado</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/github_mongodb-csharp.png" medium="image">
			<media:title type="html">mongodb-csharp @ github</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/norm_logo.png" medium="image">
			<media:title type="html">NoRM logo</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/github_download_source.png" medium="image">
			<media:title type="html">Download Source</media:title>
		</media:content>
	</item>
		<item>
		<title>No-SQL &#8211; MongoDB &#8211; Da introdução a utilização em alto nível em C# com NoRM.</title>
		<link>http://fredzvt.wordpress.com/2010/04/10/no-sql-mongodb-da-introducao-a-utilizacao-em-alto-nivel-em-csharp-com-norm/</link>
		<comments>http://fredzvt.wordpress.com/2010/04/10/no-sql-mongodb-da-introducao-a-utilizacao-em-alto-nivel-em-csharp-com-norm/#comments</comments>
		<pubDate>Sun, 11 Apr 2010 01:35:21 +0000</pubDate>
		<dc:creator>fredzvt</dc:creator>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[No-SQL]]></category>
		<category><![CDATA[NoRM]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[couchdb]]></category>
		<category><![CDATA[databases]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[mongodb-csharp]]></category>

		<guid isPermaLink="false">http://fredzvt.wordpress.com/?p=31</guid>
		<description><![CDATA[Conheça um pouco sobre o movimento No-SQL, sobre o banco de dados MongoDB e como utilizá-lo em seus projetos em C# utilizando o driver mongodb-csharp e a biblioteca NoRM.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fredzvt.wordpress.com&amp;blog=12849895&amp;post=31&amp;subd=fredzvt&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div style="background-color:#F0F0F0;margin-bottom:10px;">
Click <a href="http://fredzvt.wordpress.com/2010/04/24/no-sql-mongodb-from-introduction-to-high-level-usage-in-csharp-with-norm/">here</a> to read the english version of this article.
</div>
<p>Neste artigo tentarei fazer uma introdução ao movimento No-SQL, a base de dados orientada a documentos MongoDB e três formas de utilizá-la: via <em>shell</em>, via o <em>driver</em> para C# mongodb-csharp e via a biblioteca NoRM.</p>
<p>O objetivo deste artigo é que o leitor tome conhecimento do que é e de como utilizar de forma básica o MongoDB, para isso os exemplos de utilização que percorreremos são intencionalmente simples e não visam explorar as diversas formas de se executar uma operação no MongoDB tampouco demostrar toda a sua capacidade.</p>
<p><span id="more-31"></span></p>
<p>Por favor, tenham em mente de que eu ainda estou estudando o software e ainda não possuo experiência prática em projetos utilizando o MongoDB, tendo meu conhecimento limitado por meus estudos particulares e, embora tenha feito todo o esforço para garantir em fontes confiáveis a veracidade das informações até o momento de sua escrita e testado em meu computador todos os exemplos de códigos aqui citados não posso dar maiores garantias. Críticas construtivas e correções serão extremamente bem vindas.</p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">Conteúdo</h2>
<ul>
<li><a href="#no-sql">No-SQL</a>
<ul>
<li><a href="#no-sql-ou-relacionais">No-SQL ou bases relacionais!? Os dois!</a></li>
</ul>
</li>
<li>
    <a href="#mongodb">MongoDB</a></p>
<ul>
<li><a href="#mongodb-vs-couchdb">MongoDB vs CouchDB</a></li>
<li><a href="#instalacao-mongodb">Instalação e inicialização do servidor do MongoDB</a></li>
</ul>
</li>
<li><a href="#mongo-shell">Utilizando o MongoDB com o Mongo shell</a></li>
<li><a href="#mongodb-csharp">Utilizando o MongoDB com o mongodb-csharp</a></li>
<li><a href="#NoRM">Utilizando o MongoDB com o NoRM</a></li>
<li><a href="#Atualizacoes">Atualizações após a publicação deste artigo</a></li>
</ul>
<p><a name="no-sql"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">No-SQL</h2>
<p>Existem hoje várias bases de dados que rompem com os requisitos clássicos atendidos pelos sistemas gerenciadores de bases de dados relacionais e tem como principais características:</p>
<div style="background-color:#eee;padding:5px;">
<p><img class="alignright size-thumbnail wp-image-36" title="Not only SQL" style="border:none;" src="http://fredzvt.files.wordpress.com/2010/04/nosql.png?w=150&#038;h=88" alt="" width="150" height="88" /></p>
<ul>
<li>O não-uso de SQL como API de consulta. (exemplos de APIs utilizadas incluem JSON, BSON, REST, RPC, etc.)</li>
<li>Não garantem operações atômicas (não-ACID).</li>
<li>Distribuídas e escaláveis horizontalmente.</li>
<li>O abandono aos esquemas pré-definidos.</li>
<li>O armazenamento de dados em um modelo não-tabular (ex: key-value, object, graphs, etc.)</li>
</ul>
<p style="font-size:smaller;margin-bottom:0;line-height:100%;padding:5px 15px;">OBS: Nem todos os bancos de dados categorizados como No-SQL possuem todas essas características, uns possuem umas, outros outras, alguns todas.</p>
</div>
<p style="margin-top:18px;">O esforço da comunidade de desenvolvimento e evangelização dessas novas abordagens tecnológicas foi nomeado de <strong>No-Sql</strong> e vem fazendo muito barulho desde o início de 2009. No-SQL deveria ser entendido como &#8220;Not only SQL&#8221; (Não somente SQL) apesar dessa interpretação não ser muito óbvia, em minha opinião. Faria mais sentido pra mim se tivesse sido rotulada de No-Relational.</p>
<p>A listagem mais completa de bases de dados que podem ser enquadradas como parte do movimento No-Sql que eu encontrei está em <a href="http://nosql-database.org/" target="_blank">http://nosql-database.org/</a>. Quando escrevi este artigo, haviam 47 lá distribuídas entre diversas categorias.</p>
<p>No blog <a href="http://escalabilidade.com/2010/03/08/introducao-ao-nosql-parte-i/" target="_blank">Escalabilidade</a> existe uma introdução bacana de bases No-SQL sob o ponto de vista de escalabilidade.</p>
<p>Aqui foco em <strong>MongoDB</strong>, que junto com CouchDB foram as que mais me interessaram desde que comecei a pesquisar sobre o assunto.</p>
<p><a name="no-sql-ou-relacionais"></a></p>
<h3>No-SQL ou bases relacionais!? Os dois!</h3>
<p>Chamo atenção para que não pensem que bases não relacionais representam uma substituição as bases relacionais. O ideal é que você conheça os prós e contras de cada software e os utilize da melhor forma possível nos cenários que encontrar.</p>
<p>Acredito que o cenário de geração de relatórios computados sobre uma grande base de dados seja o alvo mais óbvio de críticas. Essas situações são resolvidas de forma excelente dando bom uso as bases de dados relacionais e sistemas de <em>Data Warehouse</em> agregando de forma frequente os dados armazenados em bases não relacionais dando suporte as aplicações de produção.</p>
<p><a href="http://blog.wekeroad.com/2010/02/05/reporting-in-nosql" target="_blank">Rob Conery</a> escreveu um excelente artigo sobre este tópico.</p>
<p><a name="mongodb"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">MongoDB</h2>
<p><img src="http://fredzvt.files.wordpress.com/2010/04/logo-mongodb.png?w=150&#038;h=62" alt="" title="MongoDB" width="150" height="62" style="float:right;border:none;background-color:#4C3A2C;margin:5px;padding:5px;" /><a href="http://www.mongodb.org/" target="_blank">MongoDB</a> é uma base de dados escalável de alta performance orientada a documentos com esquema dinâmico que tenta apresentar o melhor dos mundos entre os sistemas de armazenamento baseados em chaves/valores (<em>key/values</em>) onde os valores são estruturados como documentos <a href="http://www.json.org/" target="_blank">JSON</a> e os sistemas gerenciadores de bancos de dados relacionais atuais com recursos como vários modelos de indexação e consultas dinâmicas.</p>
<p>Seu nome, cá para nós brasileiros, soa muito mal. Mas, em inglês, vem de &#8220;<em>humongous</em>&#8221; (algo gigante), talvez com tom sarcástico por ser um software tão pequeno e com recursos tão poderosos ou talvez por ser escalável até se tornar algo realmente monstruoso. Vai saber&#8230;</p>
<p>Hoje <a href="http://www.mongodb.org/display/DOCS/Production+Deployments" target="_blank">é usado em produção</a> por pelo menos 40 sites de alto acesso e performance, incluindo sites como <em><a href="http://sourceforge.net/" target="_blank">SourceForge</a></em>, <em><a href="http://github.com/" target="_blank">GitHub</a></em>, <em><a href="http://www.ea.com/" target="_blank">EA</a></em> e <em><a href="http://www.nytimes.com/" target="_blank">The New York Times</a></em>.</p>
<p><a name="mongodb-vs-couchdb"></a></p>
<h3>MongoDB vs CouchDB</h3>
<p>Apesar de <a href="http://www.mongodb.org/" target="_blank">MongoDB</a> e <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> <a href="http://www.mongodb.org/display/DOCS/Comparing+Mongo+DB+and+Couch+DB" target="_blank">apresentarem diferenças</a> em suas abordagens de implementação em aspectos tais como versionamento e controle de concorrência, escalabilidade, API de consulta, etc, e ainda que ambos sejam projetos de código livre, ainda os considero como softwares concorrentes por oferecerem recursos similares. Acredito que o MongoDB leve uma grande vantagem e irá se desenvolver mais rapidamente visto que é escrito em C++ e não em <a href="http://www.erlang.org/index.html" target="_blank">Erlang</a>, como o CouchDB.</p>
<p><a name="instalacao-mongodb"></a></p>
<h3>Instalação e inicialização do servidor do MongoDB</h3>
<p>O MongoDB pode ser baixado em versões compiladas para Linux, OS X e Windows. Para os exemplos deste artigo vou usar a versão 1.4.0 compilada para Windows 64-bits mas acredito não haver diferenças usando a versão 32-bits.</p>
<p><img src="http://fredzvt.files.wordpress.com/2010/04/mongodb_folders.jpg?w=168&#038;h=156" alt="" title="MongoDB Folders" width="168" height="156" style="float:right;border:none;margin:5px;padding:5px;" />Quando terminar de baixar o arquivo zip, descompacte-o em uma pasta qualquer de seu computador. Serão criadas quatro diretórios: bin, include, lib e lib64. As pastas include, lib e lib64 são utilizadas para quem for utilizar o MongoDB programando em C++, no nosso caso o que interessa é a aplicação <em>mongod.exe</em> dentro da pasta bin, que é o servidor do MongoDB.</p>
<p>Por padrão, o MongoDB utiliza a pasta <em>c:\data\db</em> como caminho padrão para suas bases de dados <strong>mas essa pasta não é criada automaticamente</strong>, portanto <strong>crie-as antes de executar o servidor</strong>. Se preferir usar outra pasta para o armazenamento das bases, inicialize o servidor com o parâmetro <span style="background-color:#111111;color:#EEEEEE;"><code>&ndash;&ndash;dbpath [caminho da pasta]</code></span>. Eu, particularmente, gosto de utilizar também o parâmetro <span style="background-color:#111111;color:#EEEEEE;"><code>&ndash;&ndash;directoryperdb</code></span> que faz com que o MongoDB crie uma subpasta para cada base que for criada. Enfim, executando o <em>mongod.exe</em> o servidor será inicializado por padrão em <em>localhost</em>, na porta <em>27017</em>.</p>
<div id="attachment_79" class="wp-caption alignnone" style="width: 687px"><a href="http://fredzvt.files.wordpress.com/2010/04/mongod_iniciado.jpg"><img src="http://fredzvt.files.wordpress.com/2010/04/mongod_iniciado.jpg?w=700" alt="" title="mongod_iniciado"   class="size-full wp-image-79" /></a><p class="wp-caption-text">Console com o mongod.exe iniciado e esperando por conexões.</p></div>
<p>A seguir, executaremos as quatro operações básicas de manipulação de dados (CRUD) e consultas simples em uma base de testes no MongoDB utilizando o Mongo <em>shell</em>, em C# com o driver <em><a href="http://github.com/samus/mongodb-csharp" target="_blank">mongdb-csharp</a></em> e em alto nível utilizando a biblioteca <em><a href="http://wiki.github.com/atheken/NoRM/" target="_blank">NoRM</a></em>.</p>
<p><a name="mongo-shell"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">Utilizando o MongoDB com o Mongo shell</h2>
<p>O executável mongo.exe é o Mongo <strong><em>shell</em></strong>. Execute-o sem parâmetros e o <em>shell</em> inicializará conectado ao servidor MongoDB em sua porta padrão (27017).</p>
<p>Entre com o comando <span style="background-color:#111111;color:#EEEEEE;"><code>show dbs</code></span> e serão listadas as bases de dados que existem: inicialmente <em>admin</em>, <em>local</em> e <em>test</em>. Por padrão o <em>shell</em> inicializa configurado para utilizar a base <em>test</em>. Para alterar a base que receberá nossos comandos, utilize o comando <span style="background-color:#111111;color:#EEEEEE;"><code>use [nome da base]</code></span>. A criação de novas bases se dá automaticamente ao posicionarmos o <em>shell</em> em uma base não existente e inserirmos algum dado nela.</p>
<p>Vamos agora inserir nosso primeiro documento em nossa nova base, efetivamente criando-a. Entre com o comando <span style="background-color:#111111;color:#EEEEEE;"><code>use minhabase</code></span>, isso irá posicionar o <em>shell</em> na base inexistente <em>minhabase</em>. Neste momento a base ainda não existirá, você pode confirmar isso utilizando o comando <span style="background-color:#111111;color:#EEEEEE;"><code>show dbs</code></span> novamente. Agora vamos usar o comando <span style="background-color:#111111;color:#EEEEEE;"><code>db.[nome da coleção].save(<em>[documento JSON]</em>)</code></span> para criar e salvar um documento, note que o documento deverá ser escrito utilizando a notação de objetos em Javascript (<a href="http://www.json.org/" target="_blank">JSON</a>). Entre com o comando: <span style="background-color:#111111;color:#EEEEEE;"><code>db.Pessoas.save({ nome: "Fred", idade: 28 })</code></span> e agora com o comando <span style="background-color:#111111;color:#EEEEEE;"><code>db.Pessoas.save({ nome: "Carlos", idade: 30 })</code></span>. Pronto, agora temos uma base de nome <em>minhabase</em> com uma coleção de nome <em>Pessoas</em> e dois documentos JSON nessa coleção: um representando uma pessoa de nome <em>Fred</em> com 28 anos e outro representando uma pessoa de nome <em>Carlos</em> de 30 anos.</p>
<p>Existem duas limitações extras em documentos <a href="http://www.json.org/" target="_blank">JSON</a> escritos para serem armazenados pelo MongoDB: os nomes das chaves não poderão iniciar com $ ou terem . (pontos) em qualquer lugar. Portanto, documentos como <code>{ $teste : 1 }</code> ou <code>{ "teste.chave" : "valor" }</code> serão inválidos.</p>
<p>Uma das características mais interessantes de bases de dados No-SQL orientadas a documentos é a não restrição de esquemas em uma coleção. Em outras palavras, uma coleção pode ter documentos cujas estruturas sejam completamente diferentes. Para quem está acostumado com bancos de dados relacionais onde cada documento (registro) só pode ter o formato pré-definido pela tabela que o contém, esta é uma grande mudança de paradigma. Para exemplificar isso, vamos adicionar um novo documento em nossa coleção que não se estruture como os dois anteriores que incluímos. Entre com o comando <span style="background-color:#111111;color:#EEEEEE;"><code>db.Pessoas.save({ primeironome: "Joaquim", sobrenome:"Silva", idade: "15 anos" })</code></span>. Com este comando acabamos de inserir na coleção <em>Pessoas</em> um documento com uma estrutura completamente diferente dos documentos anteriores e é absolutamente válido.</p>
<p>Uma vez com os dados armazenados, o próximo passo será consultar esses dados. No <em>shell</em>, as consultas são realizadas através do comando <span style="background-color:#111111;color:#EEEEEE;"><code>db.[nome da coleção].find(...)</code></span>. Se executarmos este comando sem nenhum parâmetro ele irá listar todos os documentos de uma coleção, portanto <span style="background-color:#111111;color:#EEEEEE;"><code>db.Pessoas.find()</code></span> irá retornar os três documentos que você acabou de inserir. O comando <em>find</em> pode ser utilizado de muitas formas, nos permitindo executar quaisquer consultas que imaginarmos em nossas coleções. Esse é um dos excelentes recursos do MongoDB em que ele se destaca de várias outras bases No-SQL. Para exemplificarmos um pouco (bem pouco mesmo!) este recurso, vamos executar uma consulta com um critério simples: para retornar somente o documento que representa a pessoa chamada <em>Fred</em> executaríamos <span style="background-color:#111111;color:#EEEEEE;"><code>db.Pessoas.find({ nome: "Fred" })</code></span>. O comando <em>find</em>, além de outros comandos do MongoDB recebem como parâmetro um documento JSON como uma especificação de critérios para que o comando somente se aplique aos objetos da coleção que possuem propriedades que o satisfazem.</p>
<p>Note que o documento retornado possui uma propriedade além das que declaramos explicitamente: a propriedade <strong><em>_id</em></strong>. Todo documento armazenado no MongoDB possui um <em>_id</em> que será único para cada documento em uma coleção. Podemos declará-lo explicitamente na criação do documento ou o MongoDB irá criar automaticamente um objeto do tipo <em>ObjectID</em> e atribuir ao mesmo. Essa propriedade constitui o principal identificador de um documento no MongoDB e será idexado por padrão em todas as coleções. A propriedade <em>_id</em> não tem obrigatoriedade de ser um <em>ObjectID</em>, podendo ser de qualquer tipo suportado por documentos JSON (<a href="http://www.mongodb.org/display/DOCS/BSON" target="_blank">na verdade BSON</a>), mas o uso de identificadores <em>ObjectID</em> é recomendado por facilitar a escalabilidade de bases MongoDB. </p>
<p>Para excluir um documento da coleção, utilizaremos o comando <span style="background-color:#111111;color:#EEEEEE;"><code>db.[nome da coleção].remove(<em>[documento-critério JSON]</em>)</code></span>, portanto, para removermos o documento que representa a pessoa chamada Carlos, executaríamos <span style="background-color:#111111;color:#EEEEEE;"><code>db.Pessoas.remove({ nome: "Carlos" })</code></span>.</p>
<p>Para atualizarmos um documento da coleção, vamos antes buscar o objeto que desejamos alterar, modificar uma de suas propriedades e salvá-lo novamente na base, efetivamente atualizando-o. O <em>shell</em> nos disponibiliza um comando muito útil para quando precisamos obter um único documento de uma coleção para manipulá-lo: o comando <span style="background-color:#111111;color:#EEEEEE;"><code>db.[nome da coleção].findOne(<em>[documento-critério JSON]</em>)</code></span>, portando executando o comando <span style="background-color:#111111;color:#EEEEEE;"><code>joaquim = db.Pessoas.findOne({ primeironome: "Joaquim" });</code></span> obteremos na variável <em>joaquim</em> uma instância do documento para manipulação. Agora podemos alterá-lo e salvá-lo novamente na coleção: execute <span style="background-color:#111111;color:#EEEEEE;"><code>joaquim.sobrenome = "Souza";</code></span> para alterar seu sobrenome e <span style="background-color:#111111;color:#EEEEEE;"><code>db.Pessoas.save(joaquim);</code></span> para atualizar o documento na base de dados.</p>
<p>Ao meu ver, o <em>shell</em> é a principal interface de administração do MongoDB, embora seu uso principal seja através de <em>drivers</em> específicos por linguagem de programação. Todos os recursos do MongoDB podem ser acessados através do <em>shell</em>, tornar-se íntimo dessa ferramente ajudará muito o seu trabalho com bases de dados MongoDB. Veja a <a href="http://www.mongodb.org/display/DOCS/mongo+-+The+Interactive+Shell" target="_blank">documentação do <em>shell</em></a> no site oficial do MongoDB.</p>
<p><a name="mongodb-csharp"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">Utilizando o MongoDB com o mongodb-csharp</h2>
<p>Assim como o <em>shell</em> é a interface entre <em>humanos-MongoDB</em> os <a href="http://www.mongodb.org/display/DOCS/Drivers" target="_blank"><em>drivers</em></a> são as interfaces entre <em>softwares-MongoDB</em>. Hoje existem <em>drivers</em> para 25 linguagens de programação. Somente para a <em>framework .NET</em> existem 6 <em>drivers</em>/ferramentas, segundo <a href="http://deserialized.com/about/" target="_blank">Bryan Migliorisi</a> em um <a href="http://deserialized.com/the-state-of-mongodb-and-csharp/" target="_blank">artigo em seu blog</a> e, dentre esses, o <a href="http://github.com/samus/mongodb-csharp#readme" target="_blank">mongodb-csharp</a>, desenvolvido por uma trupe liderada por <a href="http://twitter.com/samcorder" target="_blank">Sam Corder</a>, é o mais maduro até o momento.</p>
<p><img src="http://fredzvt.files.wordpress.com/2010/04/github_mongodb-csharp.png?w=700" alt="" title="mongodb-csharp @ github"   class="alignleft size-full wp-image-118" style="border:none;" />Uma pequena crítica ao projeto vai apenas para a documentação precária, acho que ao menos o <em>wiki</em> do projeto deveria conter alguns exemplos dos recursos porém é possível entender o funcionamento da maioria deles analisando os projetos de testes. Acredito que isso irá melhorar com o tempo pois o projeto ainda é bastante embrionário.</p>
<p>Neste artigo usaremos a <a href="http://github.com/samus/mongodb-csharp/downloads" target="_blank">versão 0.82.2 do mongodb-csharp</a> para executar nossas operações de testes em nosso código. Sua <em>API</em> é bastante similar a do <em>shell</em>, tornando ainda mais fácil a nossa vida.</p>
<p>Descompactando o arquivo do download, teremos três bibliotecas dinâmicas: <code>MongoDB.Driver.dll</code>, <code>MongoDB.GridFS.dll</code> e <code>MongoDB.Linq.dll</code>. A que devemos adicionar como referência em nosso projeto é a <code>MongoDB.Driver.dll</code>. As outras duas são, respectivamente, uma <em>API</em> para a utilização do suporte à especificação <a href="http://www.mongodb.org/display/DOCS/GridFS" target="_blank">GridFS</a>, que permite o armazenamento de objetos binários com mais de 4MB no MongoDB e o suporte básico a LINQ.</p>
<p>A primeira coisa que devemos fazer em nosso código para utilizar o MongoDB é conectar ao servidor:</p>
<p><pre class="brush: csharp;">
using MongoDB.Driver;

Mongo mongo = new Mongo();
mongo.Connect();
</pre></p>
<p>Em seguida, devemos obter uma referência à base de dados e à coleção que queremos manipular:</p>
<p><pre class="brush: csharp;">
Database db = mongo.GetDatabase(&quot;minhabase&quot;);
IMongoCollection collection = db.GetCollection(&quot;Pessoas&quot;);
</pre></p>
<p>A classe <code>MongoDB.Driver.Document</code> representa um documento do MongoDB e funciona de forma muito semelhante a um <code>System.Collections.Generic.Dictionary&lt;String, Object&gt;</code>:</p>
<p><pre class="brush: csharp;">
Document doc = new Document();
doc.Add(&quot;nome&quot;, &quot;Guilherme&quot;);
doc.Add(&quot;idade&quot;, 22);
</pre></p>
<p>Para persistir um novo documento na coleção referenciada:</p>
<p><pre class="brush: csharp;">
collection.Save(doc);
</pre></p>
<p>Quando executamos o comando <em>find</em> no <em>shell</em> o que retornamos é, na verdade, <a href="http://www.mongodb.org/display/DOCS/Queries+and+Cursors" target="_blank">um cursor</a> que é iterado automaticamente pelo <em>shell</em> mas que poderíamos referenciar em uma variável e manipular manualmente. O <em>mongodb-csharp</em> utiliza o mesmo princípio, mas aqui o trabalho de iteração sobre os valores será sempre manual.</p>
<p><pre class="brush: csharp;">
ICursor cur = collection.FindAll();
foreach (Document iDoc in cur.Documents)
{
    Console.WriteLine(&quot;Nome: {0}, Idade: {1}&quot;, iDoc[&quot;nome&quot;], iDoc[&quot;idade&quot;]);
}
</pre></p>
<p>Para atualizarmos um documento, o processo é, mais uma vez, semelhante ao executado no <em>shell</em>: buscar uma referência a um documento específico, alterá-lo e salvá-lo de volta a coleção:</p>
<p><pre class="brush: csharp;">
Document doc2 = collection.FindOne(new Document() {{&quot;primeironome&quot;, &quot;Joaquim&quot;}});
doc2[&quot;sobrenome&quot;] = &quot;Silva&quot;;

collection.Save(doc2);
</pre></p>
<p>E, por fim, para excluirmos um documento:</p>
<p><pre class="brush: csharp;">
collection.Delete(doc2);
collection.Delete(new Document() {{ &quot;nome&quot;, &quot;Guilherme&quot; }});
</pre></p>
<p>Simples, não!? O <em>driver mongodb-csharp</em> nos proporciona <em>APIs</em> para quase a totalidade de funcionalidades do MongoDB e é muito fácil de ser utilizado, como pudemos ver.</p>
<p><a name="NoRM"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">Utilizando o MongoDB com o NoRM</h2>
<p><img src="http://fredzvt.files.wordpress.com/2010/04/norm_logo.png?w=700" alt="" title="NoRM logo"   class="alignright size-full wp-image-144" style="border:none;" />Depois de ter conhecido a biblioteca <a href="http://wiki.github.com/atheken/NoRM/" target="_blank">NoRM</a>, quando utilizo o <em>mongodb-csharp</em> para acessar uma base MongoDB fico com um gosto amargo de baixo nível em minha boca, lembro-me da época em que acessava bancos de dados com <code>Recordsets</code> em ASP clássico.</p>
<p>A biblioteca NoRM proporciona uma abstração em alto nível para a manipulação de documentos em uma base MongoDB de forma fortemente tipada além de disponibilizar uma <em>API</em> mais amigável para envio de comandos a um servidor MongoDB.</p>
<p>NoRM é um projeto de código livre, assim como o <em>mongodb-csharp</em> é hospedado no <a href="http://github.com/" target="_blank">github</a>, tem <a href="http://andrewtheken.com/" target="_blank">Andrew Theken</a> como líder e principal desenvolvedor e contribuidores do peso de <a href="" target="_blank">Rob Conery</a> (a mente por trás do projeto <a href="http://www.subsonicproject.com/" target="_blank">SubSonic</a>). É um projeto tão novo que nem release tem ainda, mas que já chama <u>muita</u> atenção!</p>
<p><img src="http://fredzvt.files.wordpress.com/2010/04/github_download_source.png?w=700" alt="" title="Download Source"   class="alignleft size-full wp-image-147" style="border:none;" />Pelo fato de não ter saído release ainda, somos obrigados a baixar o código para compilarmos em nossa máquina. <a href="http://wiki.github.com/atheken/NoRM/" target="_blank">Na página do projeto no github</a>, clique no botão &#8220;Download Source&#8221; e, em seguida escolha o formato de compactação que preferir. Salve e descompacte em alguma pasta de seu computador. Ou faça um clone do repositório Git &#8212; <a href="http://blog.tinogomes.com/sobre/" target="_blank">Tino Gomes</a> <a href="http://blog.tinogomes.com/2008/05/11/instalando-e-usando-git-no-windows-xp/" target="_blank">ensina como fazer isso no Windows</a>). Abra a solução <code>NoRM.sln</code>, compile o projeto NoRM e referencie a DLL gerada em sua aplicação ou adicione o projeto <code>NoRM/NoRM.csproj</code> a solução da sua aplicação e referencie o projeto adicionado.</p>
<p>A biblioteca NoRM funciona de forma fortemente tipada, fazendo a tradução automática entre documentos BSON armazenados no MongoDB e suas classes em C# e vice-versa, portanto, vamos criar a classe <em>Pessoa</em>:</p>
<p><pre class="brush: csharp;">
class Pessoa
{
    public ObjectId ID { get; set; }
    public string Nome { get; set; }
    public int Idade { get; set; }
}
</pre></p>
<p>NoRM impõe certas convenções em nossas classes para que a serialização/deserialização seja realizada sem problemas, são elas:</p>
<ul>
<li>Os tipos suportados para serialização/deserialização (até o momento em que este artigo foi escrito) são:
<ul>
<li><code>int</code></li>
<li><code>bool</code></li>
<li><code>double</code></li>
<li><code>float</code>
<ul>
<li>Sempre será serializado/deserializado como <code>double</code></li>
</ul>
</li>
<li><code>DateTime</code></li>
<li><code>string</code></li>
<li><code>byte[]</code></li>
<li><code>Norm.ObjectId</code></li>
<li><code>Regex</code></li>
<li><code>Guid</code></li>
<li><code>Enums</code>
<ul>
<li>Deve herdar de <code>uint</code>, <code>int</code>, <code>ulong</code>, <code>long</code></li>
<p> (ex: <code>public enum meu_enum : int {...}</code>)</ul>
</li>
<li><code>Norm.ScopedCode</code></li>
<li><code>IEnumerable&lt;T&gt;</code>
<ul>
<li>T deve também ser de um dos tipos suportados</li>
<li><span style="text-decoration:line-through;">Sempre será deserializado como List&lt;T&gt;</span> <strong>Atualização:</strong></span> Como informou Andrew Theken, parece que agora temos a opção de utilizar outros tipos de coleções.</li>
</ul>
</li>
</ul>
</li>
<li>É recomendado que ao usar tipos de valor (<em>value-types</em>) deveremos ancapsulá-los em um <code>System.Nullable&lt;T&gt;</code> pois se o valor da propriedade não existir no documento BSON, será atribuído <code>null</code>. (Ex: usar <code>int?</code> ao invés de <code>int</code>)</li>
<li>Todas as classes devem possuir uma propriedade pública chamada <code>_id</code> ou <code>ID</code> sendo de qualquer um dos tipos suportados, porém se forem do tipo <code>Guid</code> ou <code>Norm.ObjectId</code> não precisaremos inicializar este valor em uma instância pois NoRM se encarregará disso.
<ul>
<li>Caso queira utilizar uma outra propriedade qualquer como identificador de seu documento poderá utilizar o atributo <code>[MongoIdentifier]</code> para tal, livrando-se da obrigatoriedade de criar uma propriedade <code>_id</code> ou <code>ID</code></li>
</ul>
</li>
<li><span style="text-decoration:line-through;">Todas as propriedades públicas deverão possuir acessores <code>get</code> e <code>set</code>.</span> <strong>Atualização:</strong></span> Como informado por Andrew Theken, o trabalho de Karl Seguin tornou possível a utilização de propriedades públicas com <code>get</code> e <code>set</code> <code>private</code> ou <code>protected</code>.</li>
<li>NoRM ainda não reconhece referências cíclicas entre classes deixando por conta do programador tomar cuidado com isso, caso contrário a execução da aplicação entrará em loop infinito.</li>
<li>NoRM ainda não resolve casos de tentativa de deserializações de tipos inválidas, por exemplo, se tentarmos deserializar um valor BSON inteiro em uma propriedade <code>DateTime</code> um erro de conversão será gerado.</li>
<li>O tamanho do documento BSON não poderá ultrapassar 4MB. (Na verdade uma limitação de qualquer documento armazenado no MongoDB que não use a especificação GridFS)</li>
<li>Os tipos <code>DateTime</code> terão precisão de milisegundos. Se presisarmos de mais precisão deveremos utilizar <code>double</code>.</li>
</ul>
<p>Sei que a primeira vista parecem muitas restrições mas ao meu ver, para um projeto cujo primeiro <em>commit</em> data de 30 de janeiro de 2010, é um feito e tanto! Lembre-se de que, se precisarmos de algo que a ferramenta não ofereça recurso poderemos criá-los e submeter um <em>patch</em> ao projeto. Além disso, tudo o que preciso para criar minhas entidades de domínio em <a href="http://en.wikipedia.org/wiki/Plain_Old_CLR_Object" target="_blank">POCOs</a> está sendo atendido.</p>
<p>Com tudo em seu lugar, vamos abrir uma conexão com o MongoDB e buscar uma referência a nossa coleção de pessoas:</p>
<p><pre class="brush: csharp;">
using Norm;
using Norm.Collections;

Mongo mongo = new Mongo(&quot;minhabase&quot;);
MongoCollection&lt;Pessoa&gt; Collection = mongo.GetCollection&lt;Pessoa&gt;(&quot;Pessoas&quot;);
</pre></p>
<p>Para inserirmos uma nova pessoa em nossa coleção bastará criar uma instância de <code>Pessoa</code> e salvá-la em nossa coleção:</p>
<p><pre class="brush: csharp;">
Pessoa Bruno = new Pessoa();
Bruno.Nome = &quot;Bruno&quot;;
Bruno.Idade = 35;

Collection.Save(Bruno);
</pre></p>
<p>Para atualizar um documento, buscamos, desta vez de forma fortemente tipada, a instância de <code>Pessoa</code> que queremos alterar passando como parâmetro de busca um tipo anônimo somente com a propriedade <em>Nome</em>, alteramos e salvamos novamente na coleção:</p>
<p><pre class="brush: csharp;">
Pessoa Bruno2Update = Collection.FindOne(new { Nome = &quot;Bruno&quot; });
Bruno2Update.Idade = 40;
Bruno2Update.Nome = &quot;Bruno Garcia&quot;;

Collection.Save(Bruno2Update);
</pre></p>
<p>Para listarmos as pessoas da coleção lindamente:</p>
<p><pre class="brush: csharp;">
IEnumerable&lt;Pessoa&gt; Pessoas = Collection.Find();
foreach (Pessoa p in Pessoas)
{
    Console.WriteLine(&quot;Nome: {0}, Idade: {1}&quot;, p.Nome, p.Idade);
}
</pre></p>
<p>E, por último, para excluirmos uma pessoa da coleção, nada mais simples:</p>
<p><pre class="brush: csharp;">
Collection.Delete(Bruno2Update);
</pre></p>
<p><a name="Atualizacoes"></a></p>
<h2 style="border-top:2px solid #EEEEEE;font-size:20px;padding-top:10px;margin:20px 0;">Atualizações após a publicação deste artigo</h2>
<p>A grande aceitação deste artigo foi uma grande surpresa para mim e eu gostaria de agradecer a todos que me deram algum tipo de feedback.</p>
<p>Gostaria de adicionar algumas notas e correções enviadas pelos leitores:</p>
<p>Antes de tudo, gostaria de deixar claro que neste artigo eu não dou preferência ao driver mongodb-csharp nem a biblioteca NoRM. Para mim ficou claro que as duas bibliotecas possuem diferentes propostas. Enquanto mongodb-csharp provê uma API de uma maneira mais similar ao shell, nos dando grande flexibilidade, NoRM se provê maior produtividade com uma abordagem um pouco mais distante do shell mas mais próximo das necessidades reais dos desenvolvedores, provendo um mapeamento direto das classes em C# de forma fortemente tipada, porém menos flexível.</p>
<p>Fiquei feliz em saber pelo Craig Wilson que logo teremos uma versão do mongodb-csharp que trás todos os recursos disponíveis pelo NoRM e algo mais.</p>
<p>Se o projeto mongodb-csharp se propôr a oferecer todos os recursos oferecidos pelo projeto NoRM e vice versa, a princípio eu daria preferência ao projeto mongodb-csharp visto que este está numa fase mais madura. Mas nesse caso não entendo porquê as duas equipes não se juntam e desenvolvem uma única biblioteca que traga o melhor dos dois mundos.</p>
<p>E, finalmente, informo que podem haver atualizações no corpo do artigo para que possa informar melhor os leitores das informações que tenho recebido. Onde houver uma correção, tacharei o texto e farei comentários.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/fredzvt.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/fredzvt.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/fredzvt.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/fredzvt.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/fredzvt.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/fredzvt.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/fredzvt.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/fredzvt.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/fredzvt.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/fredzvt.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/fredzvt.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/fredzvt.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/fredzvt.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/fredzvt.wordpress.com/31/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fredzvt.wordpress.com&amp;blog=12849895&amp;post=31&amp;subd=fredzvt&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://fredzvt.wordpress.com/2010/04/10/no-sql-mongodb-da-introducao-a-utilizacao-em-alto-nivel-em-csharp-com-norm/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/ee38139ed3fc8836d92c270c0dd83f74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mimiefred</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/nosql.png?w=150" medium="image">
			<media:title type="html">Not only SQL</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/logo-mongodb.png?w=150" medium="image">
			<media:title type="html">MongoDB</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/mongodb_folders.jpg" medium="image">
			<media:title type="html">MongoDB Folders</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/mongod_iniciado.jpg" medium="image">
			<media:title type="html">mongod_iniciado</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/github_mongodb-csharp.png" medium="image">
			<media:title type="html">mongodb-csharp @ github</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/norm_logo.png" medium="image">
			<media:title type="html">NoRM logo</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/04/github_download_source.png" medium="image">
			<media:title type="html">Download Source</media:title>
		</media:content>
	</item>
		<item>
		<title>Abra o prompt de comando direto de uma pasta no Windows Explorer (Windows 2000+).</title>
		<link>http://fredzvt.wordpress.com/2010/03/30/abra-cmd-direto-do-shell/</link>
		<comments>http://fredzvt.wordpress.com/2010/03/30/abra-cmd-direto-do-shell/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 09:29:19 +0000</pubDate>
		<dc:creator>fredzvt</dc:creator>
				<category><![CDATA[Eu uso e recomendo]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://fredzvt.wordpress.com/?p=22</guid>
		<description><![CDATA[Iniciar &#62; Executar &#62; Cmd &#62; cd..., cd..., cd..., cd...
Cansado disso? Seus problemas acabaram! :D<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fredzvt.wordpress.com&amp;blog=12849895&amp;post=22&amp;subd=fredzvt&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Essa dica será útil a todos que estão cansados de abrir o command prompt do Windows e ter que navegar manualmente até uma pasta específica para realizar uma tarefa.</p>
<p><span id="more-22"></span></p>
<p>Existem diversas maneiras de adicionar um comando no menu de contexto do <a title="Não sabe o que é shell do Windows? Veja aqui! (em inglês)" href="http://en.wikipedia.org/wiki/Windows_shell" target="_blank">shell do windows</a> (veja <a title="Cinco métodos alternativos para adicionar o comando ao shell." href="http://www.petri.co.il/add_command_prompt_here_shortcut_to_windows_explorer.htm" target="_blank">esse blog post</a> para uma descrição de vários métodos) mas, que eu saiba, nenhuma melhor ou mais simples e prática do que a <a title="Open Command Prompt Shell Extension" href="http://code.kliu.org/cmdopen/" target="_blank">pequena aplicação</a> desenvolvida pelo simpático chinês <a title="Sobre o Kai Liu." href="http://www.kailiu.com/about.xhtml" target="_blank">Kai Liu</a>. E ainda coloca uma opção para abrir o prompt como administrador em casos de Windows que utilizam o UAC (Windows Vista, Windows 7, etc.).</p>
<div id="attachment_24" class="wp-caption aligncenter" style="width: 507px"><a href="http://code.kliu.org/cmdopen/"><img class="size-full wp-image-24" title="cmdopen-2.0-menus" src="http://fredzvt.files.wordpress.com/2010/03/cmdopen-2-0-menus.png?w=700" alt="Open Command Prompt Shell Extension"   /></a><p class="wp-caption-text">Open Command Prompt Shell Extension</p></div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/fredzvt.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/fredzvt.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/fredzvt.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/fredzvt.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/fredzvt.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/fredzvt.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/fredzvt.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/fredzvt.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/fredzvt.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/fredzvt.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/fredzvt.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/fredzvt.wordpress.com/22/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/fredzvt.wordpress.com/22/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/fredzvt.wordpress.com/22/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fredzvt.wordpress.com&amp;blog=12849895&amp;post=22&amp;subd=fredzvt&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://fredzvt.wordpress.com/2010/03/30/abra-cmd-direto-do-shell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/ee38139ed3fc8836d92c270c0dd83f74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mimiefred</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/03/cmdopen-2-0-menus.png" medium="image">
			<media:title type="html">cmdopen-2.0-menus</media:title>
		</media:content>
	</item>
		<item>
		<title>Transforme seu laptop com Windows 7 em um Wi-Fi hotspot com o Connectify.</title>
		<link>http://fredzvt.wordpress.com/2010/03/28/transforme-seu-laptop-em-wifi-hotspot-com-connectify/</link>
		<comments>http://fredzvt.wordpress.com/2010/03/28/transforme-seu-laptop-em-wifi-hotspot-com-connectify/#comments</comments>
		<pubDate>Sun, 28 Mar 2010 18:06:14 +0000</pubDate>
		<dc:creator>fredzvt</dc:creator>
				<category><![CDATA[Eu uso e recomendo]]></category>
		<category><![CDATA[Rede]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://fredzvt.wordpress.com/?p=4</guid>
		<description><![CDATA[Conheça uma pequena aplicação de muito fácil utilização que transforma seu laptop com Windows 7 em um WiFi Hotspot.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fredzvt.wordpress.com&amp;blog=12849895&amp;post=4&amp;subd=fredzvt&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-thumbnail wp-image-6" title="connectify" src="http://fredzvt.files.wordpress.com/2010/03/connectify.png?w=150&#038;h=30" alt="Logo do Connectify" width="150" height="30" />Descobri hoje uma ferramenta excelente, o <a title="Site do Connectify." href="http://www.connectify.me/" target="_blank">Connectify</a>.</p>
<p>Esse pequeno aplicativo transformou meu laptop com Windows 7 Ultimate em um ponto de distribuição da minha internet 3G quase como mágica! Agora eu e minha esposa podemos utilizar simultaneamente a internet, cada um em seu laptop.</p>
<p><span id="more-4"></span></p>
<p>O único problema que eu tive foi que o Windows XP do laptop da minha esposa não conseguiu conectar a rede com segurança WPA2-PSK mas que resolvi com tranquilidade, habilitando o modo Ad-Hoc WEP, que estava escondido e apareceu quando eu cliquei com o botão direito sobre o logo da aplicação Options &gt; Show all settings.</p>
<p><img class="aligncenter size-full wp-image-10" title="Connectify_Screen" src="http://fredzvt.files.wordpress.com/2010/03/connectify_screen.png?w=700" alt="Tela do Connectify."   /></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/fredzvt.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/fredzvt.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/fredzvt.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/fredzvt.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/fredzvt.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/fredzvt.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/fredzvt.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/fredzvt.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/fredzvt.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/fredzvt.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/fredzvt.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/fredzvt.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/fredzvt.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/fredzvt.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fredzvt.wordpress.com&amp;blog=12849895&amp;post=4&amp;subd=fredzvt&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://fredzvt.wordpress.com/2010/03/28/transforme-seu-laptop-em-wifi-hotspot-com-connectify/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/ee38139ed3fc8836d92c270c0dd83f74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mimiefred</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/03/connectify.png?w=150" medium="image">
			<media:title type="html">connectify</media:title>
		</media:content>

		<media:content url="http://fredzvt.files.wordpress.com/2010/03/connectify_screen.png" medium="image">
			<media:title type="html">Connectify_Screen</media:title>
		</media:content>
	</item>
	</channel>
</rss>
