<?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>Blog Patrick Espake</title>
	<atom:link href="http://blog.patrickespake.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.patrickespake.com</link>
	<description>O conhecimento evolui quando é compartilhado!</description>
	<lastBuildDate>Tue, 09 Mar 2010 15:31:26 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>MongoDB do feijão a feijoada</title>
		<link>http://blog.patrickespake.com/2010/03/09/mongodb-do-feijao-a-feijoada/</link>
		<comments>http://blog.patrickespake.com/2010/03/09/mongodb-do-feijao-a-feijoada/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 15:05:32 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[alta performance]]></category>
		<category><![CDATA[atualização]]></category>
		<category><![CDATA[características]]></category>
		<category><![CDATA[coleção]]></category>
		<category><![CDATA[conceitos]]></category>
		<category><![CDATA[conexão]]></category>
		<category><![CDATA[consulta]]></category>
		<category><![CDATA[documental]]></category>
		<category><![CDATA[documento]]></category>
		<category><![CDATA[escalável]]></category>
		<category><![CDATA[índices]]></category>
		<category><![CDATA[inserção]]></category>
		<category><![CDATA[insert]]></category>
		<category><![CDATA[instalação]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[mongo]]></category>
		<category><![CDATA[mongod]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[operadores]]></category>
		<category><![CDATA[remove]]></category>
		<category><![CDATA[shell]]></category>
		<category><![CDATA[update]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1119</guid>
		<description><![CDATA[
Combina as melhores características de banco de dados documental, armazenamento de chave-valores e banco de dados relacional.
MongoDB é uma solução escalável, de alta performance, open source e banco de dados orientado a documentos. Escrito em C++, algumas características:

Armazenamento orientando a documentos (a simplicidade e poder do esquemas de dados em JSON);
Consultas dinâmicas;
Completo suporte a índices, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/03/feijoada.jpg"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/03/feijoada.jpg" alt="" title="feijoada" width="245" height="245" class="aligncenter size-full wp-image-1128" /></a></p>
<p>Combina as melhores características de banco de dados documental, armazenamento de chave-valores e banco de dados relacional.</p>
<p>MongoDB é uma solução escalável, de alta performance, open source e banco de dados orientado a documentos. Escrito em C++, algumas características:</p>
<ul>
<li>Armazenamento orientando a documentos (a simplicidade e poder do esquemas de dados em JSON);</li>
<li>Consultas dinâmicas;</li>
<li>Completo suporte a índices, extendo para objetos internos e arrays embutidos;</li>
<li>Rápido, para atualizações;</li>
<li>Eficiente armazenamento de dados binários, como: fotos e vídeos;</li>
<li>Auto-sharding alto nível de escabilidade na nuvem;</li>
<li>MapReduce para agregação complexa;</li>
<li>&#8230;</li>
</ul>
<p>MongoDB é a ponte do fosso entre o armazenamento de chave-valores (que são rápidos e altamente escaláveis) e os tradicionais banco de dados relacionais (que fornecem esquemas estruturados e consultas poderosas).</p>
<h2>Conceitos</h2>
<p><strong>Coleções</strong></p>
<p>Coleções são essecialmente nomes de grupos de documentos. Você pode pensar nelas mais ou menos equivalente às tabelas do banco de dados relacional.</p>
<p>Estes documentos usualmente tem a mesma estrutura, mas isso não é um exigência do MongoDB o esquema de dados é livre. Você pode armazenar conjunto  heterogêneo de documentos dentro de uma coleção, você não precisa predefinir &#8220;colunas&#8221; ou campos para as coleções.</p>
<p>Os nomes das coleções podem começar com letras, underscore ou podem incluir números; $ é reservado não podendo ser usado.</p>
<p><strong>Documentos</strong></p>
<p>Quando nós inserimos dados no MongoDB, os dados sempre são na forma de documentos. Documentos são uma estrutura de dados análogo ao JSON, dicionários em Python, e hashes em Ruby. Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">doc = { author : 'joe', created : new Date('03-28-2009'), ... }</pre></div></div>

<p><strong>(BSON) Tipos de dados</strong></p>
<p>MongoDB usa tipos de dados especiais além dos tipos básicos JSON de string, integer, boolean, double, null, array e object. Esses tipos incluem date, object id, dados binários, expressão regular e código.</p>
<p><strong>Object IDs</strong></p>
<p>Documentos no MongoDB são obrigados a ter uma chave, _id, única para a sua identificação.</p>
<p>Cada documento no MongoDB tem um campo _id como primeiro atributo. Esse valor usualmente é BSON ObjectId, sendo único para cada membro da coleção.</p>
<p>Se o usuário tentar inserir um documento sem fornecer um id, o banco de dados irá gerar automaticamente um _object id e armazená-lo no campo _id.</p>
<p>Usuários podem gerar suas próprias convenções para criação de ids; o valor para _id pode ser de qualquer tipo enquanto for único.</p>
<h2>Instalação</h2>
<p><a href="http://www.mongodb.org/display/DOCS/Quickstart">http://www.mongodb.org/display/DOCS/Quickstart</a></p>
<p>Para iniciar o processo do MongoDB:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ mongod</pre></div></div>

<h2>Conexão com o banco de dados</h2>
<p>Você pode manipular o banco de dados através do shell JavaScript com:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ mongo</pre></div></div>

<p>Por padrão o shell conecta no banco de dados em localhost. Você verá:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">MongoDB shell version: 1.2.2
url: <span style="color: #7a0874; font-weight: bold;">test</span>
connecting to: <span style="color: #7a0874; font-weight: bold;">test</span>
<span style="color: #7a0874; font-weight: bold;">type</span> <span style="color: #ff0000;">&quot;help&quot;</span> <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #7a0874; font-weight: bold;">help</span>
<span style="color: #000000; font-weight: bold;">&gt;</span></pre></div></div>

<p>&#8220;connecting to:&#8221; informa para você o nome do banco de dados que o shell está usando. Para mudar para outro banco de dados, digite:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; use mydb</pre></div></div>

<p>Para ver toda a lista de comandos válidos, digite help.</p>
<p><em>Para os desenvolvedores mais experiêntes em outros banco de dados, você pode notar que nunca é criado o banco de dados ou coleção, MongoDB não solicita isso. Quando você inserir algo o MongoDB cria a coleção e o banco de dados. Se você consultar uma coleção que não existe o MongoDB trata como uma coleção vazia.</em></p>
<h2>Inserindo dados em uma coleção</h2>
<p>Para começar vamos criar uma coleção de teste e inserir alguns dados. Nós vamos criar dois objetos, j e t, e então salvar eles na coleção <em>things</em>.</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; j = { name: &quot;mongo&quot; };
{ &quot;name&quot; : &quot;mongo&quot; }
&gt; t = { x: 3 };
{ &quot;x&quot; : 3 }
&gt; db.things.save(j);
&gt; db.things.save(t);
&gt; db.things.find();
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f478dbe0e0f149e074e&quot;), &quot;name&quot; : &quot;mongo&quot; }
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f4e8dbe0e0f149e074f&quot;), &quot;x&quot; : 3 }
&gt;</pre></div></div>

<p>Algumas coisas para notar:</p>
<ul>
<li>Nós não temos uma coleção pré-definida. O banco de dados cria automaticamente na primeira inserção;</li>
<li>Os documentos que nós gravamos podem ter qualquer &#8220;estrutura&#8221; &#8211; na verdade nesse exemplo, os documentos não tem elementos de dados comum a todos. Na prática, usualmente os documentos tem a mesma estrutura dentro das coleções. No entando, esta flexibilidade significa que as migrações de esquema e de reposição são muito mais fáceis na prática &#8211; raramente você vai precisar escrever um script que executa operações do tipo &#8220;alter table&#8221;;</li>
<li>Ao ser inserido no banco de dados, os objetos são atribuídos a um identificador de objeto (se ele não tiver um) no campo _id;</li>
</ul>
<p>Vamos adicionar mais alguns registros para esta coleção:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; for( var i=1; i &lt; 10; i++) db.things.save({ x:4, j:i });
&gt; db.things.find();
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f478dbe0e0f149e074e&quot;), &quot;name&quot; : &quot;mongo&quot; }
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f4e8dbe0e0f149e074f&quot;), &quot;x&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0750&quot;), &quot;x&quot; : 4, &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0751&quot;), &quot;x&quot; : 4, &quot;j&quot; : 2 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0752&quot;), &quot;x&quot; : 4, &quot;j&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0753&quot;), &quot;x&quot; : 4, &quot;j&quot; : 4 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0754&quot;), &quot;x&quot; : 4, &quot;j&quot; : 5 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0755&quot;), &quot;x&quot; : 4, &quot;j&quot; : 6 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0756&quot;), &quot;x&quot; : 4, &quot;j&quot; : 7 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0757&quot;), &quot;x&quot; : 4, &quot;j&quot; : 8 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0758&quot;), &quot;x&quot; : 4, &quot;j&quot; : 9 }
&gt;</pre></div></div>

<p>Note que vamos ver os dois documentos adicionados no começo e mais os 9 novos documentos adicionados no loop for.</p>
<h2>Acessando dados da consulta</h2>
<p>Tecnicamente, find() retorna um objeto cursor, desta forma é possível iterar em cima dele em um loop while:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; var cursor = db.things.find();
&gt; while (cursor.hasNext()) { print(tojson(cursor.next())); }
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f478dbe0e0f149e074e&quot;), &quot;name&quot; : &quot;mongo&quot; }
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f4e8dbe0e0f149e074f&quot;), &quot;x&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0750&quot;), &quot;x&quot; : 4, &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0751&quot;), &quot;x&quot; : 4, &quot;j&quot; : 2 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0752&quot;), &quot;x&quot; : 4, &quot;j&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0753&quot;), &quot;x&quot; : 4, &quot;j&quot; : 4 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0754&quot;), &quot;x&quot; : 4, &quot;j&quot; : 5 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0755&quot;), &quot;x&quot; : 4, &quot;j&quot; : 6 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0756&quot;), &quot;x&quot; : 4, &quot;j&quot; : 7 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0757&quot;), &quot;x&quot; : 4, &quot;j&quot; : 8 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0758&quot;), &quot;x&quot; : 4, &quot;j&quot; : 9 }
&gt;</pre></div></div>

<p>O exemplo acima exibe o estilo de iteração usando o cursor. A funcão hasNext() informa se existe mais documentos para retornar, e a função next() retorna o próximo documento. Nós usamos o método tojson() para formatar os documentos para JSON.</p>
<p>Ao trabalhar com o shell JavaScript, também podemos usar os recursos da linguagem, e apenas chamar forEach para o cursor.</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find().forEach( function(x) { print(tojson(x));  } );
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f478dbe0e0f149e074e&quot;), &quot;name&quot; : &quot;mongo&quot; }
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f4e8dbe0e0f149e074f&quot;), &quot;x&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0750&quot;), &quot;x&quot; : 4, &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0751&quot;), &quot;x&quot; : 4, &quot;j&quot; : 2 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0752&quot;), &quot;x&quot; : 4, &quot;j&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0753&quot;), &quot;x&quot; : 4, &quot;j&quot; : 4 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0754&quot;), &quot;x&quot; : 4, &quot;j&quot; : 5 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0755&quot;), &quot;x&quot; : 4, &quot;j&quot; : 6 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0756&quot;), &quot;x&quot; : 4, &quot;j&quot; : 7 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0757&quot;), &quot;x&quot; : 4, &quot;j&quot; : 8 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0758&quot;), &quot;x&quot; : 4, &quot;j&quot; : 9 }
&gt;</pre></div></div>

<p>Nesse caso do forEach() devemos definir uma função que é chamada para cada documento no cursor.</p>
<p>No shell do MongoDB, você pode tratar cursores como um array:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; var cursor = db.things.find();
&gt; print (tojson(cursor[4]));
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0752&quot;), &quot;x&quot; : 4, &quot;j&quot; : 3 }</pre></div></div>

<p>Ao usar um cursor assim, note que todos os valores até o mais alto acessado (cursor[4] acima) são carregados na memória RAM ao mesmo tempo. Isso não é apropriado para grandes conjuntos de resultados, você pode ficar sem memória. Cursores devem ser usados com um iterador com qualquer consulta que retornar um grande número de elementos.</p>
<p>Também é possível converter o cursor para um array:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; var arr = db.things.find().toArray();
&gt; arr[5];
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0753&quot;), &quot;x&quot; : 4, &quot;j&quot; : 4 }</pre></div></div>

<p>Por favor note que esses recursos de array são específicos do shell interativo do MongoDB, e não disponíveis em todos os drivers para MongoDB.</p>
<h2>Especificando o que a consulta retorna</h2>
<p>Agora que sabemos como trabalhar com cursores, podemos nós concentrar para as consultas retornarem coisas específicas.</p>
<p>Em geral, a maneira de fazer isso é criar &#8220;documentos de consulta&#8221;, que são documentos que indicam o padrão de chaves e valores que devem ser combinados.</p>
<p>Estes são mais fáceis demonstrar que explicar. No exemplos a seguir, vamos dar o exemplo da consulta SQL, e demonstrar a forma de representar a mesma consulta usando MongoDB através o shell. Esta maneira de consultas específicas é fundamental para MongoDB, assim que você vai encontrar a mesma facilidade em alguns driver ou linguagens.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> things <span style="color: #993333; font-weight: bold;">WHERE</span> name<span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;mongo&quot;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find({name:&quot;mongo&quot;}).forEach(function(x) { print(tojson(x)); } );
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f478dbe0e0f149e074e&quot;), &quot;name&quot; : &quot;mongo&quot; }</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> things <span style="color: #993333; font-weight: bold;">WHERE</span> x<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">4</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find({x:4}).forEach(function(x) { print(tojson(x)); });
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0750&quot;), &quot;x&quot; : 4, &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0751&quot;), &quot;x&quot; : 4, &quot;j&quot; : 2 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0752&quot;), &quot;x&quot; : 4, &quot;j&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0753&quot;), &quot;x&quot; : 4, &quot;j&quot; : 4 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0754&quot;), &quot;x&quot; : 4, &quot;j&quot; : 5 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0755&quot;), &quot;x&quot; : 4, &quot;j&quot; : 6 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0756&quot;), &quot;x&quot; : 4, &quot;j&quot; : 7 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0757&quot;), &quot;x&quot; : 4, &quot;j&quot; : 8 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0758&quot;), &quot;x&quot; : 4, &quot;j&quot; : 9 }</pre></div></div>

<p>A expressão de consulta é um documento em si. O documento de consulta é da forma { a:A, b:B, &#8230; } significa &#8220;where a==A and b==B and &#8230;&#8221;.</p>
<p>MongoDB também permite que você retorne &#8220;documentos parciais&#8221; &#8211; documentos que tenham apenas um subconjunto de elementos do documento armazenado em banco de dados. Para fazer isso, você adiciona um segundo argumento para a consulta find(), fornecendo um documento que enumera os elementos que devem ser devolvidos.</p>
<p>Para ilustar, vamos repetir o último exemplo find({x:4}) com o argumento adicional que limita o documento devolvido apenas com os elementos &#8220;j&#8221;:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> j <span style="color: #993333; font-weight: bold;">FROM</span> things <span style="color: #993333; font-weight: bold;">WHERE</span> x<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">4</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find({x:4}, {j:true}).forEach(function(x) { print(tojson(x)); });
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0750&quot;), &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0751&quot;), &quot;j&quot; : 2 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0752&quot;), &quot;j&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0753&quot;), &quot;j&quot; : 4 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0754&quot;), &quot;j&quot; : 5 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0755&quot;), &quot;j&quot; : 6 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0756&quot;), &quot;j&quot; : 7 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0757&quot;), &quot;j&quot; : 8 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0758&quot;), &quot;j&quot; : 9 }</pre></div></div>

<p>Note que o campo &#8220;_id&#8221; sempre é retornado.</p>
<h2>findOne()</h2>
<p>Por conveniência, o MongoDB shell (e outros drivers) permite evitar sobrecarga de programação de lidar com o cursor, e só permite recuperar um documento através da função findOne(). findOne() utiliza os mesmos parâmetros que a função find(), mas ao invés de retornar um cursor, ele irá retornar primeiro documento retornado do banco de dados, ou null se nenhum documento for encontrado com a consulta especificada.</p>
<p>Como exemplo, podemos recuperar um documento com o name==&#8217;mongo&#8217;. Há muitas maneiras de fazer isso, incluindo apenas chamar next() do cursor (após verificar se não é nulo, é claro), ou tratar o curso como um array e acessando o elemento zero.</p>
<p>No entando, o método findOne() é conveniente e eficiênte:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; var mongo = db.things.findOne({name:&quot;mongo&quot;});
&gt; print(tojson(mongo));
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f478dbe0e0f149e074e&quot;), &quot;name&quot; : &quot;mongo&quot; }</pre></div></div>

<p>Isso é mais eficiênte porque que o cliente requisita um único objeto do banco de dados, assim menos trabalho é necessário pelo banco de dados e rede. Isso é equivalente a find({name:&#8221;mongo&#8221;}).limit(1);</p>
<h2>Limitar o Result Set através de limit()</h2>
<p>Você pode limitar a quantidade de resultados da consulta definindo o máximo de número de resultados para serem retornados através do método limit().</p>
<p>Isso é altamente recomendável por razões de desempenho, isso limita o trabalho que o banco de dados faz, e limita o montante de dados retornados pela rede. Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find().limit(3);
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f478dbe0e0f149e074e&quot;), &quot;name&quot; : &quot;mongo&quot; }
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f4e8dbe0e0f149e074f&quot;), &quot;x&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0750&quot;), &quot;x&quot; : 4, &quot;j&quot; : 1 }</pre></div></div>

<h2>Índices</h2>
<p>Índices podem melhorar o desempenho da consulta, muitas vezes damaticamente. É importante pensar sobre os tipos de consulta da sua aplicação que você possa definir índices relevantes. Atualmente criar índices no MongoDB é relativamente fácil.</p>
<p>Um índice é uma estrutura de dado em coleção sobre os valores dos campos especificados nos documentos de uma coleção. Essa estrutura de dados é usado pelo otimizador de consulta do MongoDB para classificar rapidamente e ordenar documentos em uma coleção. Formalmente, esses índices são implementados usando índices &#8220;B-Tree&#8221;.</p>
<p>No shell, você pode criar um índice chamando a função ensureIndex(), e fornecendo um documento que especifica uma ou mais chaves de índice. Como exemplo nós podemos criar um índice para os campos &#8220;j&#8221;:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.ensureIndex({j:1});</pre></div></div>

<p>A função ensureIndex() apenas cria o índice se ele não existir.</p>
<p>Uma vez que uma coleção é indexada por uma chave, o acesso aleatório a uma consulta que combina com a achave específica é rápido. Sem o índice o MongoDB tem que passar por cada documento, verificando o valor da chave especificada na consulta:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find({j:2}); // rápido - usando índice
{ &quot;_id&quot; : ObjectId(&quot;4b7f13c38dbe0e0f149e0751&quot;), &quot;x&quot; : 4, &quot;j&quot; : 2 }
&gt; db.things.find({x:3}); // lento - tem que verificar todos porque 'x' não tem índice
{ &quot;_id&quot; : ObjectId(&quot;4b7f0f4e8dbe0e0f149e074f&quot;), &quot;x&quot; : 3 }</pre></div></div>

<h2>Chaves embutidas</h2>
<p>Com MongoDB você pode indexar até mesmo uma chave dentro de um documento embutido. Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.ensureIndex({&quot;address.city&quot;:1});</pre></div></div>

<h2>Documentos como chaves</h2>
<p>Campos indexados pode ser de qualquer tipo, incluíndo documentos:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.factories.save( { name: &quot;xyz&quot;, metro: { city: &quot;New York&quot;, state: &quot;NY&quot; } } );
&gt; db.factories.ensureIndex({metro:1});</pre></div></div>

<p>Você não pode especificar a classificação e ordenação para uma chave de objeto, portanto, as chaves de objetos são úteis para recuperação aleatória, menos para acessos ordenados (para esse último, considere chave de índices compostos).</p>
<h2>Índices de chaves compostas</h2>
<p>Além de chave única para índices, MongoDB também suporta múltiplas chaves &#8220;compostas&#8221; para índices. Assim como nos índices simples você usa a função ensureIndex() para criar o índice, mas em vez de especificar somente uma chave, você pode especificar várias:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.ensureIndex({j:1, name:-1});</pre></div></div>

<p>Ao criar um índice, o número associado com a chave específica a direção do índice, assim sempre deve ser 1 (ascedente) ou -1 (descendente). Direção não importa para índices de chave única ou para acesso aleatório, mas é importante se você estiver fazendo consultas amplas sobre índices compostos.</p>
<p>Se você tiver um índice composto em múltiplos campos, você pode usá-lo para consulta no subconjunto dos campos. Por exemplo, se você tiver o índice composto nos campos:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">a, b, c</pre></div></div>

<p>Você pode usá-lo em consulta para:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">a</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">a, b</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">a, b, c</pre></div></div>

<h2>Índices únicos</h2>
<p>MongoDB suporta índices únicos, o que garante que não existem documentos já inseridos, cujos valores para as chaves indexadas coincidem com os de um documento existente. Para criar um índice que garante que não existem dois documentos que têm os mesmos valores para x e j você pode fazer:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.ensureIndex({x:1, j:1}, {unique:true});</pre></div></div>

<h2>Chaves perdidas</h2>
<p>Quando o documento é salvado na coleção com índices únicos, as chaves faltantes serão inseridas com valores nulo. Assim, não será possível a inserção de múltiplos documentos em falta com a mesma chave indexada.</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.people.save({firstname: &quot;Patrick&quot;, lastname: &quot;Espake&quot;});
&gt; db.people.ensureIndex({firstname: 1}, {unique: true});
&gt; db.people.save({lastname: &quot;Smith&quot;});
&gt; db.people.save({lastname: &quot;Jones&quot;});
E11000 duplicate key errorindex: mydb.people.$firstname_1  dup key: { : null }
&gt; db.people.find()
{ &quot;_id&quot; : ObjectId(&quot;4b841fdd07c6c3b400e7fe3e&quot;), &quot;firstname&quot; : &quot;Patrick&quot;, &quot;lastname&quot; : &quot;Espake&quot; }
{ &quot;_id&quot; : ObjectId(&quot;4b84200f07c6c3b400e7fe3f&quot;), &quot;lastname&quot; : &quot;Smith&quot; }</pre></div></div>

<h2>Valores duplicados</h2>
<p>O índice único não pode ser criado em uma chave que tem valores duplicados. Se você quiser criar o índice mesmo assim, mantendo o primeiro documento no banco de dados e apagando todos os outros documentos que tenha valores duplicados, adicione a opção dropDups.</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.ensureIndex({firstname : 1}, {unique : true, dropDups : true})</pre></div></div>

<h2>Apagando índices</h2>
<p>Para apagar todos os índices de uma coleção específica:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.collection.dropIndexes();</pre></div></div>

<p>Para apagar um único índice:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.collection.dropIndex({x: 1, y: -1})</pre></div></div>

<h2>ReIndex</h2>
<p>O comando reIndex vai reconstruir todos os índices da coleção:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.myCollection.reIndex()</pre></div></div>

<p>Usualmente isso é desnecessário. Você pode pedir para fazer se o tamanho da sua coleção mudou drasticamente ou o espaço em disco usado pelos índices parece estranhamente grande.</p>
<h2>Desempenho dos índices</h2>
<p>Índices fazem a busca por chave, incluíndo a recuperação sequencial ordenada, muito rápido. Atualizações por chave são rápidas também, MongoDB pode buscar o documento e atualizar rapidamente.</p>
<p>No entanto, tenha em mente que cada índice criado adiciona uma certa quantidade de sobrecarga para as inserções e exclusões. Além de escrever dados na base de coleções, as chaves devem ser adicionadas aos índices B-Tree. Assim, índices são melhores para coleções onde o número de leituras e muito maior que o número de escritas. Para coleções que são escritas intensamente, índices, em alguns casos podem ser anti-produtivos. A maioria das coleções são de leitura intensa, por isso os índices são uma coisa boa na maioria das situações.</p>
<h2>Usando sort() sem um índice</h2>
<p>Você pode usar sort() para retornar dados em ordem sem um índice, se o conjunto de dados a ser devolvido é pequeno (menor que quatro megabytes). Para outros casos é melhor user limit() e sort() juntos.</p>
<h2>Multikeys</h2>
<p>MongoDB fornece um interessante recurso &#8220;multikey&#8221; que pode automaticamente indexar arrays de valores de um objeto. Um bom exemplo são tags. Suponha que você tenha um artigo com tags que sejam alguns nomes de categorias:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.articles.save({ name: &quot;Warm Weather&quot;, author: &quot;Steve&quot;, tags: ['weather', 'hot', 'record', 'april'] });
&gt; db.articles.find()                                                           
{ &quot;_id&quot; : ObjectId(&quot;4b842cad07c6c3b400e7fe42&quot;), &quot;name&quot; : &quot;Warm Weather&quot;, &quot;author&quot; : &quot;Steve&quot;, &quot;tags&quot; : [ &quot;weather&quot;, &quot;hot&quot;, &quot;record&quot;, &quot;april&quot; ] }</pre></div></div>

<p>Nós podemos facilmente executar uma consulta à procura de um determinado valor no array de tags:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.articles.find({ tags: 'april' })
{ &quot;_id&quot; : ObjectId(&quot;4b842cad07c6c3b400e7fe42&quot;), &quot;name&quot; : &quot;Warm Weather&quot;, &quot;author&quot; : &quot;Steve&quot;, &quot;tags&quot; : [ &quot;weather&quot;, &quot;hot&quot;, &quot;record&quot;, &quot;april&quot; ] }</pre></div></div>

<p>Além disso, nós podemos indexar o array de tags. Criando um índice no array de elementos de resultados na indexação do banco de dados indexando cada elemento do array:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.articles.ensureIndex( { tags: 1 } )
&gt; db.articles.find( { tags: 'april' } )
{ &quot;_id&quot; : ObjectId(&quot;4b842cad07c6c3b400e7fe42&quot;), &quot;name&quot; : &quot;Warm Weather&quot;, &quot;author&quot; : &quot;Steve&quot;, &quot;tags&quot; : [ &quot;weather&quot;, &quot;hot&quot;, &quot;record&quot;, &quot;april&quot; ] }
&gt; db.articles.find( { tags: 'april' } ).explain()
{
	&quot;cursor&quot; : &quot;BtreeCursor tags_1&quot;,
	&quot;startKey&quot; : {
		&quot;tags&quot; : &quot;april&quot;
	},
	&quot;endKey&quot; : {
		&quot;tags&quot; : &quot;april&quot;
	},
	&quot;nscanned&quot; : 1,
	&quot;n&quot; : 1,
	&quot;millis&quot; : 0,
	&quot;oldPlan&quot; : {
		&quot;cursor&quot; : &quot;BtreeCursor tags_1&quot;,
		&quot;startKey&quot; : {
			&quot;tags&quot; : &quot;april&quot;
		},
		&quot;endKey&quot; : {
			&quot;tags&quot; : &quot;april&quot;
		}
	},
	&quot;allPlans&quot; : [
		{
			&quot;cursor&quot; : &quot;BtreeCursor tags_1&quot;,
			&quot;startKey&quot; : {
				&quot;tags&quot; : &quot;april&quot;
			},
			&quot;endKey&quot; : {
				&quot;tags&quot; : &quot;april&quot;
			}
		}
	]
}</pre></div></div>

<h2>Campos de objeto embutido em um array</h2>
<p>Além disso, a mesma técnica pode ser usado para campos em objetos embutidos:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.posts.save( { title: &quot;How the west was won&quot;, comments: [ { text: &quot;great!&quot;, author: &quot;sam&quot; }, { text: &quot;ok&quot;, author: &quot;julie&quot; } ] } )
&gt; db.posts.find( { &quot;comments.author&quot;: &quot;julie&quot; } )                               
{ &quot;_id&quot; : ObjectId(&quot;4b84310707c6c3b400e7fe44&quot;), &quot;title&quot; : &quot;How the west was won&quot;, &quot;comments&quot; : [
	{
		&quot;text&quot; : &quot;great!&quot;,
		&quot;author&quot; : &quot;sam&quot;
	},
	{
		&quot;text&quot; : &quot;ok&quot;,
		&quot;author&quot; : &quot;julie&quot;
	}
] }</pre></div></div>

<h2>Consultado todos os valores definidos em um conjunto determinado</h2>
<p>Ao utilizar a opção $all na consulta, um conjunto de valores podem ser fornecidos os quais devem estar presentes em um campo de objeto correspondente. Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.articles.find( { tags: { $all: ['april', 'record'] } } )
{ &quot;_id&quot; : ObjectId(&quot;4b842cad07c6c3b400e7fe42&quot;), &quot;name&quot; : &quot;Warm Weather&quot;, &quot;author&quot; : &quot;Steve&quot;, &quot;tags&quot; : [ &quot;weather&quot;, &quot;hot&quot;, &quot;record&quot;, &quot;april&quot; ] }
&gt; db.articles.find( { tags: { $all: ['april', 'june'] } } )  
&gt; // nada encontrado</pre></div></div>

<h2>Skip e Limit</h2>
<p>MongoDB também suporta skip e limit para paginação fácil. Aqui podemos ignorar os 10 primeiros documentos, e limitar o nosso conjunto de resultados para 20:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find({}, {}, 10, 20)</pre></div></div>

<h2>Consultas avançadas</h2>
<p><strong>Operadores condicionais: <, <=, >, >=</strong></p>
<p>Use essas formas especiais para comparações maior que e menor que em consultas, desde que eles possam ser representandos em documentos de consulta:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.collection.find({ &quot;field&quot; : { $gt: value } } ); // maior que  : campo &gt; valor
&gt; db.collection.find({ &quot;field&quot; : { $lt: value } } ); // menor que  :  campo &lt; valor
&gt; db.collection.find({ &quot;field&quot; : { $gte: value } } ); // maior que ou igual : campo &gt;= valor
&gt; db.collection.find({ &quot;field&quot; : { $lte: value } } ); // menor que ou igual : campo &lt;= valor</pre></div></div>

<p>Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { j: { $lt: 3 } } );
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771d&quot;), &quot;x&quot; : 10, &quot;j&quot; : 0 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771e&quot;), &quot;x&quot; : 10, &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771f&quot;), &quot;x&quot; : 10, &quot;j&quot; : 2 }
&gt; db.things.find( { j: { $gte: 4 } } ); 
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277721&quot;), &quot;x&quot; : 10, &quot;j&quot; : 4 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277722&quot;), &quot;x&quot; : 10, &quot;j&quot; : 5 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277723&quot;), &quot;x&quot; : 10, &quot;j&quot; : 6 }</pre></div></div>

<p>Você pode combinar esses operadores para intervalos específicos:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { j: { $gt: 3, $lt: 6  } } )
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277721&quot;), &quot;x&quot; : 10, &quot;j&quot; : 4 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277722&quot;), &quot;x&quot; : 10, &quot;j&quot; : 5 }</pre></div></div>

<p><strong>Operador condicional: $ne</strong></p>
<p>Use $ne para &#8220;não igual&#8221;:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { j: { $ne: 2 } } )  
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771d&quot;), &quot;x&quot; : 10, &quot;j&quot; : 0 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771e&quot;), &quot;x&quot; : 10, &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277720&quot;), &quot;x&quot; : 10, &quot;j&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277721&quot;), &quot;x&quot; : 10, &quot;j&quot; : 4 }</pre></div></div>

<p><strong>Operador condicional: $in</strong></p>
<p>O operador $in é análogo ao modificador SQL IN, permite que você especifique um array de combinação:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { j: { $in: [2, 4, 6] } } )
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771f&quot;), &quot;x&quot; : 10, &quot;j&quot; : 2 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277721&quot;), &quot;x&quot; : 10, &quot;j&quot; : 4 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277723&quot;), &quot;x&quot; : 10, &quot;j&quot; : 6 }</pre></div></div>

<p><strong>Operador condicional: $nin</strong></p>
<p>O operador $nin é similar ao $in exceto que seleciona objetos que não tem nenhum valor especificado no array. Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { j: { $nin: [2,4,6] } } );
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771d&quot;), &quot;x&quot; : 10, &quot;j&quot; : 0 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771e&quot;), &quot;x&quot; : 10, &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277720&quot;), &quot;x&quot; : 10, &quot;j&quot; : 3 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277722&quot;), &quot;x&quot; : 10, &quot;j&quot; : 5 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277724&quot;), &quot;x&quot; : 10, &quot;j&quot; : 7 }</pre></div></div>

<p><strong>Operador condicional: $mod</strong></p>
<p>O operador $mod permite que você faça consultas rápidas usando módulo:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { j: { $mod: [ 10, 1 ] } } ) // this.a % 10 == 1
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771e&quot;), &quot;x&quot; : 10, &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277728&quot;), &quot;x&quot; : 10, &quot;j&quot; : 11 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e99277732&quot;), &quot;x&quot; : 10, &quot;j&quot; : 21 }</pre></div></div>

<p><strong>Operador condicional: $all</strong></p>
<p>O operador $all é similar ao $in, mas ao invés combinar qualquer valor do array, deve combinar todos os valores especificados no array. Por exemplo, o objeto:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">{ a: [1, 2, 3] }</pre></div></div>

<p>Deve combinar com:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">db.things.find( { a: { $all: [ 2, 3 ] } } );</pre></div></div>

<p>mas não com:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">db.things.find( { a: { $all: [ 2, 3, 4 ] } } );</pre></div></div>

<p><strong>Operador condicional: $size</strong></p>
<p>O operador $size permite especificar o tamanho de um array, ou seja, a quantidade de elementos:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { j: { $size: 1 } } )
{ &quot;_id&quot; : ObjectId(&quot;4b8580965b4e024e99277781&quot;), &quot;j&quot; : [ 99 ] }
{ &quot;_id&quot; : ObjectId(&quot;4b85809b5b4e024e99277782&quot;), &quot;j&quot; : [ 999 ] }
{ &quot;_id&quot; : ObjectId(&quot;4b85809e5b4e024e99277783&quot;), &quot;j&quot; : [ 9999 ] }
{ &quot;_id&quot; : ObjectId(&quot;4b8580a15b4e024e99277784&quot;), &quot;j&quot; : [ 99990000 ] }</pre></div></div>

<p><strong>Operador condicional: $exists</strong></p>
<p>Verifica pela existência (ou ausência) de um campo:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { a: { $exists: true } } )
&gt; db.things.find( { a: { $exists: false } } )
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771d&quot;), &quot;x&quot; : 10, &quot;j&quot; : 0 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771e&quot;), &quot;x&quot; : 10, &quot;j&quot; : 1 }</pre></div></div>

<p><strong>Expressões regulares</strong></p>
<p>Você pode usar expressões regulares para consultas:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.customers.find( { name : /acme.*corp/i } );</pre></div></div>

<p><strong>Valores em um Array</strong></p>
<p>Você pode buscar todas as coleções que possuam a cor vermelha no array de cores:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { colors : &quot;red&quot; } );</pre></div></div>

<p><strong>Operador condicional: $elemMatch</strong></p>
<p>Use $elemMatch para verificar se um elemento no array combina com a expressão de combinação especificada:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { x: { $elemMatch: { a:1, b: { $gt: 1 } } } } )</pre></div></div>

<p><strong>Operador meta: $not</strong></p>
<p>O operador meta $not pode ser usado para negar a verificação realizada por um operador padrão. Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { x: { $not: { $mod: [10, 1] } } } );</pre></div></div>

<p><strong>Expressão de linguagem e $where</strong></p>
<p>Além da sintaxe estruturada de consulta mostrada até agora, você pode escrever consultas com a expressão &#8220;where&#8221; no estilo SQL.</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { $where: &quot;this.j &lt; 3&quot; } )
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771d&quot;), &quot;x&quot; : 10, &quot;j&quot; : 0 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771e&quot;), &quot;x&quot; : 10, &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771f&quot;), &quot;x&quot; : 10, &quot;j&quot; : 2 }
&gt; db.things.find(&quot;this.j &lt; 3&quot;)              
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771d&quot;), &quot;x&quot; : 10, &quot;j&quot; : 0 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771e&quot;), &quot;x&quot; : 10, &quot;j&quot; : 1 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771f&quot;), &quot;x&quot; : 10, &quot;j&quot; : 2 }</pre></div></div>

<h2>sort()</h2>
<p>sort() é análogo ao ORDER BY no padrão SQL. Em MongoDB o valor 1 indica a ordem crescente e o -1 indica a ordem descrecente.</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find().sort( { x:1 } ) // classifica em ordem crescente
&gt; db.things.find().sort( { x:-1 } ) // classifica em ordem decrescente</pre></div></div>

<h2>limit()</h2>
<p>limit() é análogo ao LIMIT no padrão SQL. Especifica a quantidade máxima de resultados devolvidos.</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find().limit(2)
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771d&quot;), &quot;x&quot; : 10, &quot;j&quot; : 0 }
{ &quot;_id&quot; : ObjectId(&quot;4b856c065b4e024e9927771e&quot;), &quot;x&quot; : 10, &quot;j&quot; : 1 }</pre></div></div>

<h2>count()</h2>
<p>O método count() retorna o número de objetos que combinam com a consulta especificada.</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.things.find( { j: { $mod: [2, 0] } } ).count()
53
&gt; db.mycollection.count( { active:true } )</pre></div></div>

<h2>Elemento do array por posição</h2>
<p>Os elementos do array também pode ser acessados por sua posição específica:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">// exemplo: comments[0].by == &quot;Abe&quot;
&gt; db.blogposts.find( { &quot;comments.0.by&quot; : &quot;Abe&quot; } )</pre></div></div>

<h2>Operações OU em expressões de consultas</h2>
<p>Objetos de consulta em MongoDB por padrão usam expressão AND para junção. MongoDB atualmente não incluem nenhum operador OR para consultas, entretanto existe algums modos de expressar isso em consultas.</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.mycollection.find( { $where : function() { return this.a == 3 || this.b == 4; } } );
&gt; db.mycollection.find( function() { return this.a == 3 || this.b == 4; } );
&gt; db.things.find(&quot;this.j == 1 || this.j == 3&quot;)</pre></div></div>

<h2>Distinct</h2>
<p>Devolve a lista de valores distintos para a chave na coleção:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.addresses.save({&quot;zip-code&quot;: 10010})
&gt; db.addresses.save({&quot;zip-code&quot;: 10010})
&gt; db.addresses.save({&quot;zip-code&quot;: 99701})
&gt; db.addresses.distinct(&quot;zip-code&quot;);
[ 10010, 99701 ]</pre></div></div>

<p>distinct também pode ser usado para chaves aninhadas:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&gt; db.comments.save({&quot;user&quot;: {&quot;points&quot;: 25}})
&gt; db.comments.save({&quot;user&quot;: {&quot;points&quot;: 31}})
&gt; db.comments.save({&quot;user&quot;: {&quot;points&quot;: 25}})
&gt; db.comments.distinct(&quot;user.points&quot;);
[ 25, 31 ]</pre></div></div>

<h2>Atualizando documentos</h2>
<p>Vamos criar um documento para depois atualizar:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">db.users.save({name: 'Johnny', languages: ['ruby', 'c']});</pre></div></div>

<p>Para atualizar o documento:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">db.users.update({name: 'Johnny'}, {name: 'Cash', languages: ['english']});</pre></div></div>

<h2>Operadores de atualização</h2>
<p>MongoDB suporta atualizações parciais de documentos. Por exemplo, você pode definir um valor:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">db.users.update({name: 'Cash'}, {'$set': {'age': 50} });</pre></div></div>

<p>É possível adicionar e remover itens dos arrays:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">db.users.update({name: 'Sue'}, {'$pull': {'languages': 'scala'} });
db.users.update({name: 'Sue'}, {'$push': {'languages': 'ruby'} });</pre></div></div>

<h2>Apagando Dados</h2>
<p>Para apagar tudo da coleção:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">db.scores.remove();</pre></div></div>

<p>Para apagar os documentos que casam com uma consulta:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">db.users.remove({name: 'Sue'});</pre></div></div>

<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.patrickespake.com%2F2010%2F03%2F09%2Fmongodb-do-feijao-a-feijoada%2F&amp;linkname=MongoDB%20do%20feij%C3%A3o%20a%20feijoada"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/03/09/mongodb-do-feijao-a-feijoada/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Internet 2009 em números</title>
		<link>http://blog.patrickespake.com/2010/03/04/internet-2009-em-numeros/</link>
		<comments>http://blog.patrickespake.com/2010/03/04/internet-2009-em-numeros/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 00:10:11 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[WEB]]></category>
		<category><![CDATA[2009]]></category>
		<category><![CDATA[américa do norte]]></category>
		<category><![CDATA[américa latina]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[aplusk]]></category>
		<category><![CDATA[ásia]]></category>
		<category><![CDATA[austrália]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[blogs]]></category>
		<category><![CDATA[caribe]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[e-mail]]></category>
		<category><![CDATA[europa]]></category>
		<category><![CDATA[facebook]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[flickr]]></category>
		<category><![CDATA[Google GFE]]></category>
		<category><![CDATA[hulu]]></category>
		<category><![CDATA[iis]]></category>
		<category><![CDATA[internet]]></category>
		<category><![CDATA[internet explorer]]></category>
		<category><![CDATA[Mídia Social]]></category>
		<category><![CDATA[mundo]]></category>
		<category><![CDATA[navegadores]]></category>
		<category><![CDATA[Nginx]]></category>
		<category><![CDATA[nomes de domínio]]></category>
		<category><![CDATA[números]]></category>
		<category><![CDATA[oceania]]></category>
		<category><![CDATA[opera]]></category>
		<category><![CDATA[other]]></category>
		<category><![CDATA[pessoas]]></category>
		<category><![CDATA[rede social]]></category>
		<category><![CDATA[safari]]></category>
		<category><![CDATA[servidores web]]></category>
		<category><![CDATA[sites]]></category>
		<category><![CDATA[software maliciosos]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[usuarios]]></category>
		<category><![CDATA[vídeos]]></category>
		<category><![CDATA[worldwide]]></category>
		<category><![CDATA[youtube]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1104</guid>
		<description><![CDATA[
O que aconteceu na internet em 2009?
Quantos sites foram adicionados? Quantos e-mails foram enviados? Quantos usuários estavam na Internet? Esse post vai responder essas questões e muitas outras. Prepara-se para a sobrecarga de informações, mas em um bom caminho. ;-)
Divirta-se!

JESS3 / The State of The Internet from JESS3 on Vimeo.
E-mail

90 trilhões &#8211; O número de [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/03/4295546056_e6a1fab7f0_o.jpg"><img class="aligncenter size-full wp-image-1107" title="4295546056_e6a1fab7f0_o" src="http://blog.patrickespake.com/wp-content/uploads/2010/03/4295546056_e6a1fab7f0_o.jpg" alt="" width="580" height="112" /></a></p>
<p>O que aconteceu na internet em 2009?</p>
<p>Quantos sites foram adicionados? Quantos e-mails foram enviados? Quantos usuários estavam na Internet? Esse post vai responder essas questões e muitas outras. Prepara-se para a sobrecarga de informações, mas em um bom caminho. ;-)</p>
<p>Divirta-se!</p>
<p><object width="600" height="450"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=9641036&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=ffffff&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=9641036&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=ffffff&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="600" height="450"></embed></object>
<p><a href="http://vimeo.com/9641036">JESS3 / The State of The Internet</a> from <a href="http://vimeo.com/jessesaves">JESS3</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<h2>E-mail</h2>
<ul>
<li><strong>90 trilhões</strong> &#8211; O número de e-mails enviados na Internet em 2009;</li>
<li><strong>247 bilhões</strong> &#8211; Número médio de mensagens de e-mail por dia;</li>
<li><strong>1,4 bilhões</strong> &#8211; O número de usuários de e-mail em todo o mundo;</li>
<li><strong>100 milhões</strong> &#8211; Novos usuários de e-mail desde o ano anterior;</li>
<li><strong>81%</strong> &#8211; A percentagem de e-mails que eram spam;</li>
<li><strong>92%</strong> &#8211; Pico do nível de spam no final do ano;</li>
<li><strong>24%</strong> &#8211; Aumento de spam desde o ano passado;</li>
<li><strong>200 bilhões</strong> &#8211; O número de e-mails de spam por dia (supondo que 81% são spam).</li>
</ul>
<h2>Sites</h2>
<ul>
<li><strong>243 milhões</strong> &#8211; O número de sites a partir de dezembro de 2009;</li>
<li><strong>47 milhões</strong> &#8211; Sites adicionados em 2009.</li>
</ul>
<h2>Servidores web</h2>
<ul>
<li><strong>13,9%</strong> &#8211; O crescimento de sites Apache em 2009;</li>
<li><strong>-22,1%</strong> &#8211; O crescimento de sites IIS em 2009;</li>
<li><strong>35,0%</strong> &#8211; O crescimento de sites Google GFE em 2009;</li>
<li><strong>384,4%</strong> &#8211; O crescimento de sites Nginx em 2009;</li>
<li><strong>-72,4%</strong> &#8211; O crescimento de sites Lighttpd em 2009.</li>
</ul>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/03/4295546152_b8e094e8cc_o.png"><img class="aligncenter size-full wp-image-1109" title="4295546152_b8e094e8cc_o" src="http://blog.patrickespake.com/wp-content/uploads/2010/03/4295546152_b8e094e8cc_o.png" alt="" width="580" height="300" /></a></p>
<h2>Nomes de domínio</h2>
<ul>
<li><strong>81,8 milhões</strong> &#8211; Nomes de domínios .COM no final de 2009;</li>
<li><strong>12,3 milhões</strong> &#8211; Nomes de domínios .NET no final de 2009;</li>
<li><strong>7,8 milhões</strong> &#8211; Nomes de domínios .ORG no final de 2009;</li>
<li><strong>76,3 milhões</strong> &#8211; O número de códigos de países no top-level de domínios (ex: .CN, .UK, .DE, etc.);</li>
<li><strong>187 milhões</strong> &#8211; O número de nomes de domínios em todo top-level de domínios (Outubro de 2009);</li>
<li><strong>8%</strong> &#8211; Aumento de nomes de domínios desde o ano anterior.</li>
</ul>
<h2>Usuários da Internet</h2>
<ul>
<li><strong>1,73 bilhões</strong> &#8211; Usuários da Internet em todo o mundo (Setembro 2009);</li>
<li><strong>18%</strong> &#8211; Crescimento de usuários da Internet desde o ano anterior;</li>
<li><strong>738.257.230</strong> &#8211; Usuários da Internet na Ásia;</li>
<li><strong>418.029.796</strong> &#8211; Usuários da Internet na Europa;</li>
<li><strong>252.908.000</strong> &#8211; Usuários da Internet na América do Norte;</li>
<li><strong>179.031.479</strong> &#8211; Usuários da Internet na América Latina e Caribe;</li>
<li><strong>67.371.700</strong> &#8211; Usuários da Internet na África;</li>
<li><strong>57.425.046</strong> &#8211; Usuários da Internet no Oriente Médio;</li>
<li><strong>20.970.490</strong> &#8211; Usuários da Internet na Oceania / Austrália.</li>
</ul>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/03/4295546114_5130d09d6a_o.png"><img class="aligncenter size-full wp-image-1111" title="4295546114_5130d09d6a_o" src="http://blog.patrickespake.com/wp-content/uploads/2010/03/4295546114_5130d09d6a_o.png" alt="" width="580" height="300" /></a></p>
<h2>Midia Social</h2>
<ul>
<li><strong>126 milhões</strong> &#8211; O número de blogs na Internet (rastreados pelo BlogPulse);</li>
<li><strong>84%</strong> &#8211; Porcentagem de sites de rede social com mais mulheres do que homens;</li>
<li><strong>27,3 milhões</strong> &#8211; Número de tweets no Twitter por dia (Novembro de 2009);</li>
<li><strong>57%</strong> &#8211; Percentagem de usuários do Twitter localizados nos Estados Unidos;</li>
<li><strong>4,25 milhões</strong> &#8211; Pessoas seguindo @aplusk (Ashton Kutcher, usuário mais seguido do Twitter);</li>
<li><strong>350 milhões</strong> &#8211; Pessoas no Facebook;</li>
<li><strong>50%</strong> &#8211; Porcentagem de usuários do Facebook que logam todos os dias;</li>
<li><strong>500.000</strong> &#8211; O número de aplicativos ativos no Facebook.</li>
</ul>
<h2>Imagens</h2>
<ul>
<li><strong>4 bilhões</strong> &#8211; Fotos armazenadas pelo Flickr (Outubro de 2009);</li>
<li><strong>2,5 bilhões</strong> &#8211; Fotos enviadas a cada mês para o Facebook;</li>
<li><strong>30 bilhões</strong> &#8211; Ao ritmo atual, o número de fotos enviadas para o Facebook por ano.</li>
</ul>
<h2>Vídeos</h2>
<ul>
<li><strong>1 bilhão</strong> &#8211; O número total de vídeos nos servidores do YouTube em um dia;</li>
<li><strong>12,2 bilhões</strong> &#8211; Vídeos vistos por mês no YouTube nos Estados Unidos (Novembro de 2009);</li>
<li><strong>924 milhões</strong> &#8211; Vídeos vistos por mês no Hulu nos Estados Unidos (Novembro de 2009);</li>
<li><strong>182</strong> &#8211; O número de vídeos online na média que um usuário assiste em um mês (EUA);</li>
<li><strong>82%</strong> &#8211; Percentagem de usuários da Internet que assistem vídeos online (EUA);</li>
<li><strong>39,4%</strong> &#8211; Vídeos publicitários armazenados no YouTube(USA);</li>
<li><strong>81,9%</strong> &#8211; Porcentagem de vídeos embutidos em blogs que são vídeos do YouTube;</li>
</ul>
<h2>Navegadores web</h2>
<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/03/4294800391_edec20a549_o.png"><img class="aligncenter size-full wp-image-1113" title="4294800391_edec20a549_o" src="http://blog.patrickespake.com/wp-content/uploads/2010/03/4294800391_edec20a549_o.png" alt="" width="580" height="300" /></a></p>
<h2>Softwares maliciosos</h2>
<ul>
<li><strong>148.000</strong> &#8211; Novos computadores zumbis criados por dia (usados em botnets para enviar spam, etc.);</li>
<li><strong>2,6 milhões</strong> &#8211; Quantidade de códigos maliciosos rodando no início de 2009 (vírus, trojans, etc.);</li>
<li><strong>921.143</strong> &#8211; O número de novas assinaturas de códigos maliciosos adicionados pela Symantec em Q4 2009.</li>
</ul>
<p>Fonte: <a href="http://royal.pingdom.com/2010/01/22/internet-2009-in-numbers/">http://royal.pingdom.com/2010/01/22/internet-2009-in-numbers/</a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.patrickespake.com%2F2010%2F03%2F04%2Finternet-2009-em-numeros%2F&amp;linkname=Internet%202009%20em%20n%C3%BAmeros"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/03/04/internet-2009-em-numeros/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Jogo Galaxis Farm Versão Beta</title>
		<link>http://blog.patrickespake.com/2010/03/03/jogo-galaxis-farm-versao-beta/</link>
		<comments>http://blog.patrickespake.com/2010/03/03/jogo-galaxis-farm-versao-beta/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 18:02:52 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Flixel]]></category>
		<category><![CDATA[Game]]></category>
		<category><![CDATA[PIBIC]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[actionscript3]]></category>
		<category><![CDATA[as]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[farm]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[galaxis]]></category>
		<category><![CDATA[galaxis farm]]></category>
		<category><![CDATA[Jogo]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[tecpar]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1095</guid>
		<description><![CDATA[
Sobre o Jogo
Galaxis Farm é um jogo de gerenciamento de tempo para plataforma Adobe Flash. Está sendo desenvolvido com a engine Flixel (http://www.flixel.org) e pode ser modificado via scripting em linguagem Lua (http://www.lua.org).
O objetivo principal deste jogo é administrar uma fazenda. É um jogo ecológico. Desta forma, o jogador também deve ser preocupar com os [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.patrickespake.com/wp-content/uploads/2010/03/telagalaxis.png"><img src="http://blog.patrickespake.com/wp-content/uploads/2010/03/telagalaxis.png" alt="" title="telagalaxis" width="643" height="401" class="aligncenter size-full wp-image-1099" /></a></p>
<h2>Sobre o Jogo</h2>
<p>Galaxis Farm é um jogo de gerenciamento de tempo para plataforma Adobe Flash. Está sendo desenvolvido com a engine Flixel (<a href="http://www.flixel.org">http://www.flixel.org</a>) e pode ser modificado via scripting em linguagem Lua (<a href="http://www.lua.org">http://www.lua.org</a>).</p>
<p>O objetivo principal deste jogo é administrar uma fazenda. É um jogo ecológico. Desta forma, o jogador também deve ser preocupar com os requisitos ambientais, atendendo, por exemplo, às legislações pertinentes de: reserva legal, mata ciliar, destinação de carcaças e tratamento de dejetos.</p>
<p>Lançado, inicialmente, para o “Concurso de Jogos em Software Livre” da Latinoware 2009 (<a href="http://www.latinoware.org/node/76">http://www.latinoware.org/node/76</a>), este jogo também serve como teste de conceito para a criação de jogos em software livre voltados para a plataforma Web.</p>
<p>Desenvolvido, portanto, com ferramentas livres, não é necessária a utilização de compiladores ou ferramentas de edição proprietárias do Adobe Flash. Pode ser compilado e modificado utilizando-se o editor aberto FlashDevelop e o framework OpenSource Flex SDK.</p>
<p>﻿Equipe envolvida, Divisão de Inteligência Artificial do TECPAR:</p>
<div id="_mcePaste">
<ul>
<li>Patrick Espake – Programação;</li>
<li>Diego Cabral – Ilustrações e design de personagens;</li>
<li>Bruno Campagnolo de Paula – Coordenação e game design;</li>
<li>Roberta Zuge – Consultoria veterinária.</li>
</ul>
</div>
<h2>Como Jogar</h2>
<p>Para jogar uma versão beta (preliminar) acesse: <a href="http://www.galaxisfarm.com/beta/">http://www.galaxisfarm.com/beta/</a> ou faça o download da versão executável: <a href="http://galaxisfarm.com/wp-content/uploads/beta_galaxisfarm.exe">http://galaxisfarm.com/wp-content/uploads/beta_galaxisfarm.exe</a></p>
<h2>Código Fonte</h2>
<p>O código fonte do jogo está disponível no Google Code em: <a href="http://code.google.com/p/galaxisfarm/">http://code.google.com/p/galaxisfarm/</a></p>
<h2>Versão Beta</h2>
<p>Atualmente o jogo está disponível na versão beta, essa versão possui as seguintes limitações:</p>
<ul>
<li>Colisão imperfeita do personagem com as construções;</li>
<li>Imagens de botões simples;</li>
<li>Efeitos visuais simples;</li>
<li>Não possui ranking;</li>
<li>Problemas nos descartes de vacas mortas.</li>
</ul>
<h2>Próxima Versão</h2>
<p>Estamos trabalhando na nova versão do jogo, nessa versão pretendemos usar a última versão da game engine Flixel, que aparentemente trabalha melhor com colisões, também vamos melhorar as imagens e efeitos visuais.</p>
<h2>Sobre a Game Engine Flixel</h2>
<p>É uma biblioteca Actionscript (Flash) livre, destinada para uma grande variedade de jogos em Flash. Inclui ganchos para gravidade e profundidade. Já possui métodos prontos para trabalhar com:</p>
<ul>
<li>Rápida renderização (+5000 sprites em computadores modernos);</li>
<li>Tilemaps;</li>
<li>Sistema de partículas;</li>
<li>Controle de volume, com teclas de atalho;</li>
<li>Parallax scrolling (multi-direcional);</li>
<li>Colisão de sprites;</li>
<li>Renderização de textos;</li>
<li>Renderização retro com opções de 2x pixels, 3x pixels, etc;</li>
<li>Não precisa da IDE do Flash, trabalha melhor com ferramentas livres como FlashDevelop;</li>
<li>Organização das classes por estados do jogo;</li>
<li>Botões simples;</li>
<li>Utilitários para loop de música e tocar som;</li>
<li>Efeitos especiais simples.</li>
</ul>
<h2>Sugestões e Críticas</h2>
<p>Ficamos no aguardo das suas sugestões e críticas a respeito do jogo.</p>
<p>Apoio Financeiro <a href="http://www.fundacaoaraucaria.org.br/">Fundação Araucária</a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.patrickespake.com%2F2010%2F03%2F03%2Fjogo-galaxis-farm-versao-beta%2F&amp;linkname=Jogo%20Galaxis%20Farm%20Vers%C3%A3o%20Beta"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/03/03/jogo-galaxis-farm-versao-beta/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MongoDB &#8211; Conceitos Básicos</title>
		<link>http://blog.patrickespake.com/2010/02/19/mongodb-conceitos-basicos/</link>
		<comments>http://blog.patrickespake.com/2010/02/19/mongodb-conceitos-basicos/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 03:35:36 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[básicos]]></category>
		<category><![CDATA[conceitos]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1091</guid>
		<description><![CDATA[MongoDB
View more presentations from Patrick Espake.

]]></description>
			<content:encoded><![CDATA[<div style="width:425px;text-align:left" id="__ss_3221865"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/patrickespake/mongodb-3221865" title="MongoDB">MongoDB</a><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=mongodb-100218212723-phpapp01&#038;stripped_title=mongodb-3221865" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=mongodb-100218212723-phpapp01&#038;stripped_title=mongodb-3221865" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">presentations</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/patrickespake">Patrick Espake</a>.</div>
</div>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.patrickespake.com%2F2010%2F02%2F19%2Fmongodb-conceitos-basicos%2F&amp;linkname=MongoDB%20%26%238211%3B%20Conceitos%20B%C3%A1sicos"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2010/02/19/mongodb-conceitos-basicos/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Novo Google Acesse Agora!!!</title>
		<link>http://blog.patrickespake.com/2009/11/25/novo-google-acesse-agora/</link>
		<comments>http://blog.patrickespake.com/2009/11/25/novo-google-acesse-agora/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 20:41:30 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Lab]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[nova interface]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1080</guid>
		<description><![CDATA[Essa é nova interface do Google.

Quer usar ela? Claro que sim!
Vamos lá!
Navegador Chrome
1) Abra o navegador Chrome;
2) Clique com o botão direito da barra de endereço;
3) Selecione a opção &#8220;Edit Search Engines&#8221;;
4) Clique na linha &#8220;Google (Default)&#8221; e no botão &#8220;Edit&#8221;;
5) Mude o keyword de &#8220;google.com.br&#8221; para &#8220;google.com&#8221;;
6) Feche a tela;
7) Acesse http://www.google.com;
8) Cole na [...]]]></description>
			<content:encoded><![CDATA[<p>Essa é nova interface do Google.</p>
<p><img src="http://blog.patrickespake.com/wp-content/uploads/2009/11/Captura_de_tela-300x168.png" alt="Captura_de_tela" title="Captura_de_tela" width="300" height="168" class="aligncenter size-medium wp-image-1082" /></p>
<p>Quer usar ela? Claro que sim!<br />
Vamos lá!</p>
<p><strong>Navegador Chrome</strong></p>
<p>1) Abra o navegador Chrome;<br />
2) Clique com o botão direito da barra de endereço;<br />
3) Selecione a opção &#8220;Edit Search Engines&#8221;;<br />
4) Clique na linha &#8220;Google (Default)&#8221; e no botão &#8220;Edit&#8221;;<br />
5) Mude o keyword de &#8220;google.com.br&#8221; para &#8220;google.com&#8221;;<br />
6) Feche a tela;<br />
7) Acesse <a href="http://www.google.com">http://www.google.com</a>;<br />
8) Cole na barra de endereço o seguinte código:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">javascript:void(document.cookie=&quot;PREF=ID=20b6e4c2f44943bb:U=4bf292d46faad806:TM=1249677602:LM=1257919388:S=odm0Ys-53ZueXfZG;path=/; domain=.google.com&quot;);</pre></div></div>

<p>9) Dê um refresh no navegador;<br />
10) Pronto! Olha a nova interface do Google!</p>
<p><img src="http://blog.patrickespake.com/wp-content/uploads/2009/11/Captura_de_tela-2-300x168.png" alt="Captura_de_tela-2" title="Captura_de_tela-2" width="300" height="168" class="aligncenter size-medium wp-image-1083" /></p>
<p><strong>Navegador Firefox</strong></p>
<p>No Firefox, é mais complicado.</p>
<p>1) Com o Firefox fechado.<br />
2) Vá em C:\Arquivos de Programas\Mozilla Firefox\searchplugins e abra o arquivo google.xml;<br />
3) Com o Bloco de Notas. Procure o texto:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;Param name=&quot;q&quot; value=&quot;{searchTerms}&quot;/&gt;</pre></div></div>

<p>4) e, depois dele, cole este texto:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;Param name=&quot;hl&quot; value=&quot;en&quot;/&gt;</pre></div></div>

<p>5) Salve e feche o arquivo;<br />
6) Abra o Firefox;<br />
7) Cole na barra de endereço o seguinte código:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">javascript:void(document.cookie=&quot;PREF=ID=20b6e4c2f44943bb:U=4bf292d46faad806:TM=1249677602:LM=1257919388:S=odm0Ys-53ZueXfZG;path=/; domain=.google.com&quot;);</pre></div></div>

<p>8) Dê um refresh no navegador;</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.patrickespake.com%2F2009%2F11%2F25%2Fnovo-google-acesse-agora%2F&amp;linkname=Novo%20Google%20Acesse%20Agora%21%21%21"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2009/11/25/novo-google-acesse-agora/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Eu odeio a FordCenter</title>
		<link>http://blog.patrickespake.com/2009/11/18/eu-odeio-a-fordcenter/</link>
		<comments>http://blog.patrickespake.com/2009/11/18/eu-odeio-a-fordcenter/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 18:42:17 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Sem categoria]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1076</guid>
		<description><![CDATA[Eu odeio a FordCenter http://www.fordcenter.com.br com todas as minhas forças! Atendimento, venda e tudo mais é uma porcaria!
]]></description>
			<content:encoded><![CDATA[<p>Eu odeio a FordCenter <a href="http://www.fordcenter.com.br">http://www.fordcenter.com.br</a> com todas as minhas forças! Atendimento, venda e tudo mais é uma porcaria!</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.patrickespake.com%2F2009%2F11%2F18%2Feu-odeio-a-fordcenter%2F&amp;linkname=Eu%20odeio%20a%20FordCenter"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2009/11/18/eu-odeio-a-fordcenter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails Paperclip com I18n</title>
		<link>http://blog.patrickespake.com/2009/11/18/ruby-on-rails-paperclip-com-i18n/</link>
		<comments>http://blog.patrickespake.com/2009/11/18/ruby-on-rails-paperclip-com-i18n/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 17:52:46 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[I18n]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[config]]></category>
		<category><![CDATA[locale]]></category>
		<category><![CDATA[paperclip]]></category>
		<category><![CDATA[pt-BR]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[yaml]]></category>
		<category><![CDATA[yml]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1073</guid>
		<description><![CDATA[O plugin paperclip não tem suporte para i18n por padrão.
Então vamos implementar isso no braço, talvez não seja a forma mais elegante do mundo, mas funciona.
No seu model:

class Ong &#60; ActiveRecord::Base
  # Paperclip
  has_attached_file :logo, :styles =&#62; &#123; :thumb =&#62; &#34;100x100&#62;&#34; &#125;
  validates_attachment_size :logo, :less_than =&#62; 50.kilobytes, :message =&#62; I18n.t&#40;'activerecord.errors.messages.attachment_size', :min =&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>O plugin paperclip não tem suporte para i18n por padrão.</p>
<p>Então vamos implementar isso no braço, talvez não seja a forma mais elegante do mundo, mas funciona.</p>
<p>No seu model:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Ong <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
  <span style="color:#008000; font-style:italic;"># Paperclip</span>
  has_attached_file <span style="color:#ff3333; font-weight:bold;">:logo</span>, <span style="color:#ff3333; font-weight:bold;">:styles</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#ff3333; font-weight:bold;">:thumb</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;100x100&gt;&quot;</span> <span style="color:#006600; font-weight:bold;">&#125;</span>
  validates_attachment_size <span style="color:#ff3333; font-weight:bold;">:logo</span>, <span style="color:#ff3333; font-weight:bold;">:less_than</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> 50.<span style="color:#9900CC;">kilobytes</span>, <span style="color:#ff3333; font-weight:bold;">:message</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> I18n.<span style="color:#9900CC;">t</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'activerecord.errors.messages.attachment_size'</span>, <span style="color:#ff3333; font-weight:bold;">:min</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">0</span>, <span style="color:#ff3333; font-weight:bold;">:max</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> 50.<span style="color:#9900CC;">kilobytes</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Agora você precisar criar a diretiva <strong>activerecord.errors.messages.attachment_size</strong> no seu config/locales/pt-BR.yml:</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">pt-BR:
  # Active Record
  activerecord:
    errors:
      template:
        header:
          one: &quot;Não foi possível gravar: 1 erro&quot;
          other: &quot;Não foi possível gravar: {{count}} erros.&quot;
        body: &quot;Por favor, verifique o(s) seguinte(s) campo(s):&quot;
      messages:
        attachment_size: &quot;tamanho do arquivo deve estar entre {{min}} e {{max}} bytes&quot;</pre></div></div>

<p>Pronto! Seja feliz!<br />
Se o plugin não faz, a gente faz.</p>
<p>Se você gostou desse texto e acha que ajudou você, me recomende: <a href="http://www.workingwithrails.com/recommendation/new/person/15479-patrick-espake"><img src="http://workingwithrails.com/images/tools/compact-small-button.jpg" alt="Recommend Me" /></a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.patrickespake.com%2F2009%2F11%2F18%2Fruby-on-rails-paperclip-com-i18n%2F&amp;linkname=Ruby%20on%20Rails%20Paperclip%20com%20I18n"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2009/11/18/ruby-on-rails-paperclip-com-i18n/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails conversão de datas com I18n</title>
		<link>http://blog.patrickespake.com/2009/11/09/ruby-on-rails-conversao-de-datas-com-i18n/</link>
		<comments>http://blog.patrickespake.com/2009/11/09/ruby-on-rails-conversao-de-datas-com-i18n/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 19:37:14 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[aplicação]]></category>
		<category><![CDATA[banco de dados]]></category>
		<category><![CDATA[conversão]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[date picker]]></category>
		<category><![CDATA[datepicker]]></category>
		<category><![CDATA[default_locale]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[format]]></category>
		<category><![CDATA[formulário]]></category>
		<category><![CDATA[I18n]]></category>
		<category><![CDATA[javascripts]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[mask]]></category>
		<category><![CDATA[new_record]]></category>
		<category><![CDATA[pt-BR]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[tag]]></category>
		<category><![CDATA[text_field]]></category>
		<category><![CDATA[value]]></category>
		<category><![CDATA[yaml]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1064</guid>
		<description><![CDATA[Eu estou desenvolvendo uma aplicação que precisa trabalhar com datas com I18n e fazer conversões para salvar a data no banco de dados e exibir para o usuário de acordo com o seu idioma.
Eu estou usando o Date Picker do jQuery em um campo do tipo text_field.

Vou mostrar um esboço de como eu fiz isso, [...]]]></description>
			<content:encoded><![CDATA[<p>Eu estou desenvolvendo uma aplicação que precisa trabalhar com datas com I18n e fazer conversões para salvar a data no banco de dados e exibir para o usuário de acordo com o seu idioma.</p>
<p>Eu estou usando o Date Picker do jQuery em um campo do tipo text_field.</p>
<p><img src="http://blog.patrickespake.com/wp-content/uploads/2009/11/datepicker.jpg" alt="datepicker" title="datepicker" width="318" height="265" class="aligncenter size-full wp-image-1068" /></p>
<p>Vou mostrar um esboço de como eu fiz isso, em primeiro lugar eu defini no arquivo config/environment.rb o idioma:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">config.<span style="color:#9900CC;">i18n</span>.<span style="color:#9900CC;">default_locale</span> = <span style="color:#996600;">'pt-BR'</span></pre></div></div>

<p>Depois eu defini no arquivo config/locales/pt-BR.yml os formatos de data:</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">pt-BR:
  date:
    formats:
      default: &quot;%d/%m/%Y&quot;
      short: &quot;%d de %B&quot;
      long: &quot;%d de %B de %Y&quot;
&nbsp;
    day_names: [Domingo, Segunda, Terça, Quarta, Quinta, Sexta, Sábado]
    abbr_day_names: [Dom, Seg, Ter, Qua, Qui, Sex, Sáb]
    month_names: [~, Janeiro, Fevereiro, Março, Abril, Maio, Junho, Julho, Agosto, Setembro, Outubro, Novembro, Dezembro]
    abbr_month_names: [~, Jan, Fev, Mar, Abr, Mai, Jun, Jul, Ago, Set, Out, Nov, Dez]
    order: [ :day, :month, :year ]</pre></div></div>

<p>No meu formulário eu deixei assim:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&lt;%</span> content_for <span style="color:#ff3333; font-weight:bold;">:javascripts</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
  <span style="color:#006600; font-weight:bold;">&lt;%</span>= include_jquery <span style="color:#006600; font-weight:bold;">%&gt;</span>
  <span style="color:#006600; font-weight:bold;">&lt;%</span>= javascript_include_tag <span style="color:#996600;">&quot;jquery.maskedinput-1.2.2.min&quot;</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
  <span style="color:#006600; font-weight:bold;">&lt;%</span> javascript_tag <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    $(document).ready(function() {
      // Adiciona date picker ao campo data de nascimento
      $.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['<span style="color:#006600; font-weight:bold;">&lt;%</span>= I18n.<span style="color:#9900CC;">locale</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>']));
      $(&quot;#investor_date_of_birth&quot;).datepicker({
        showOn: 'both',
        buttonImage: '/images/calendar.gif',
        buttonImageOnly: false,
        buttonText: '<span style="color:#006600; font-weight:bold;">&lt;%</span>= t<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'ui.admin.crud.datepicker_button_text'</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>',
        changeMonth: true,
        changeYear: true,
        yearRange: '1900:<span style="color:#006600; font-weight:bold;">&lt;%</span>= <span style="color:#CC00FF; font-weight:bold;">Time</span>.<span style="color:#9900CC;">now</span>.<span style="color:#9900CC;">year</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>'
      });
&nbsp;
      // Adiciona mascara ao campo data de nascimento
      $(&quot;#investor_date_of_birth&quot;).mask(&quot;99/99/9999&quot;);
    });
  <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&nbsp;
<span style="color:#006600; font-weight:bold;">&lt;%</span> form_for <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:admin</span>, <span style="color:#0066ff; font-weight:bold;">@investor</span><span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>f<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">-%&gt;</span>
  <span style="color:#006600; font-weight:bold;">&lt;%</span>= f.<span style="color:#9900CC;">error_messages</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&nbsp;
  <span style="color:#006600; font-weight:bold;">&lt;%</span>= f.<span style="color:#9900CC;">label</span> <span style="color:#ff3333; font-weight:bold;">:date_of_birth</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
&nbsp;
  <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0066ff; font-weight:bold;">@investor</span>.<span style="color:#9900CC;">new_record</span>? <span style="color:#006600; font-weight:bold;">%&gt;</span>
    <span style="color:#006600; font-weight:bold;">&lt;%</span>= f.<span style="color:#9900CC;">text_field</span> <span style="color:#ff3333; font-weight:bold;">:date_of_birth</span>, <span style="color:#ff3333; font-weight:bold;">:class</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;smallInput&quot;</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
  <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">else</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    <span style="color:#006600; font-weight:bold;">&lt;%</span>= f.<span style="color:#9900CC;">text_field</span> <span style="color:#ff3333; font-weight:bold;">:date_of_birth</span>, <span style="color:#ff3333; font-weight:bold;">:value</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> l<span style="color:#006600; font-weight:bold;">&#40;</span>@investor.<span style="color:#9900CC;">date_of_birth</span>, <span style="color:#ff3333; font-weight:bold;">:format</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:default</span><span style="color:#006600; font-weight:bold;">&#41;</span>, <span style="color:#ff3333; font-weight:bold;">:class</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;smallInput&quot;</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
  <span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span></pre></div></div>

<p>Caso exista o registro é realizado a conversão para exibir a data corretamente no formulário, não é necessário fazer conversão para salvar no banco de dados, o Rails já faz isso automaticamente.</p>
<p>Se você gostou desse texto e acha que ajudou você, me recomende: <a href="http://www.workingwithrails.com/recommendation/new/person/15479-patrick-espake"><img src="http://workingwithrails.com/images/tools/compact-small-button.jpg" alt="Recommend Me" /></a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.patrickespake.com%2F2009%2F11%2F09%2Fruby-on-rails-conversao-de-datas-com-i18n%2F&amp;linkname=Ruby%20on%20Rails%20convers%C3%A3o%20de%20datas%20com%20I18n"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2009/11/09/ruby-on-rails-conversao-de-datas-com-i18n/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Instalação do PostgreSQL</title>
		<link>http://blog.patrickespake.com/2009/11/09/instalacao-do-postgresql/</link>
		<comments>http://blog.patrickespake.com/2009/11/09/instalacao-do-postgresql/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 18:26:00 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[alter user]]></category>
		<category><![CDATA[apt-get]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[cliente]]></category>
		<category><![CDATA[comando]]></category>
		<category><![CDATA[configurando]]></category>
		<category><![CDATA[createdb]]></category>
		<category><![CDATA[createrole]]></category>
		<category><![CDATA[deletar]]></category>
		<category><![CDATA[dropuser]]></category>
		<category><![CDATA[exemplo]]></category>
		<category><![CDATA[host]]></category>
		<category><![CDATA[inherit]]></category>
		<category><![CDATA[instalação]]></category>
		<category><![CDATA[listen_addresses]]></category>
		<category><![CDATA[md5]]></category>
		<category><![CDATA[password]]></category>
		<category><![CDATA[php_hba.conf]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[postgresql-8.3]]></category>
		<category><![CDATA[postgresql-client-8.3]]></category>
		<category><![CDATA[postgresql-common]]></category>
		<category><![CDATA[postgresql.conf]]></category>
		<category><![CDATA[psql]]></category>
		<category><![CDATA[senha]]></category>
		<category><![CDATA[shell]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[su]]></category>
		<category><![CDATA[superuser]]></category>
		<category><![CDATA[Ubuntu]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1060</guid>
		<description><![CDATA[Instalação
Para instalar o PostgreSQL no Ubuntu digite o comando:

sudo apt-get install postgresql-common postgresql-8.3 postgresql-client-8.3

Mudando a senha do usuário postgres

sudo su postgres psql

No console do psql

ALTER USER postgres WITH PASSWORD 'postgres';
\q

Configurando o postgresql.conf

sudo vi /etc/postgresql/8.3/main/postgresql.conf

Localizar a linha:

listen_addresses = 'localhost'

e mudar para:

listen_addresses = '*'

remova o carácter de comentário (#) da linha.
A opção listen_addresses permite definir qual host [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Instalação</strong></p>
<p>Para instalar o PostgreSQL no Ubuntu digite o comando:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">apt-get</span> <span style="color: #c20cb9; font-weight: bold;">install</span> postgresql-common postgresql-<span style="color: #000000;">8.3</span> postgresql-client-<span style="color: #000000;">8.3</span></pre></div></div>

<p><strong>Mudando a senha do usuário postgres</strong></p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">su</span> postgres psql</pre></div></div>

<p>No console do psql</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">ALTER</span> USER postgres <span style="color: #993333; font-weight: bold;">WITH</span> PASSWORD <span style="color: #ff0000;">'postgres'</span>;
\q</pre></div></div>

<p><strong>Configurando o postgresql.conf</strong></p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">vi</span> <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span>postgresql<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">8.3</span><span style="color: #000000; font-weight: bold;">/</span>main<span style="color: #000000; font-weight: bold;">/</span>postgresql.conf</pre></div></div>

<p>Localizar a linha:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">listen_addresses = <span style="color: #ff0000;">'localhost'</span></pre></div></div>

<p>e mudar para:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">listen_addresses = <span style="color: #ff0000;">'*'</span></pre></div></div>

<p>remova o carácter de comentário (#) da linha.</p>
<p>A opção listen_addresses permite definir qual host pode se conectar no servidor, exemplo: localhost somente para conexões locais, * para qualquer host ou um ip específico como: 192.168.1.236.</p>
<p><strong>Configurando pg_hba.conf</strong></p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">vi</span> <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span>postgresql<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">8.3</span><span style="color: #000000; font-weight: bold;">/</span>main<span style="color: #000000; font-weight: bold;">/</span>pg_hba.conf</pre></div></div>

<p>Adicionar no fim do arquivo a linha:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">host all all 192.168.1.0<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">24</span> md5</pre></div></div>

<p>Essa configuração específica na ordem:</p>
<ul>
<li>host: Define regras para o protocolo TCP/IP, essa opção pode ser host, local ou hostssl;</li>
<li>all: Define qual banco de dados que essa regra se aplica, se definindo all será para todos;</li>
<li>all: Define qual usuário tem permissão para usar essa regra, se definido all será para todos;</li>
<li>192.168.1.0/24: Padrão CIDR, define qual faixa de ip&#8217;s podem ser conectar no servidor através do padrão CIDR;</li>
<li>md5: Método de autenticação, md5 padrão, trust para aceitar, reject para negar e mais algumas outras opções.</li>
</ul>
<p><strong>Reiniciar o PostgreSQL</strong></p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span>init.d<span style="color: #000000; font-weight: bold;">/</span>postgresql-<span style="color: #000000;">8.3</span> restart</pre></div></div>

<p><strong>Usuários de banco de dados</strong></p>
<p>Criar um novo usuário. Para pode criar um novo usuário é necessário estar logado com o usuário postgres.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">sudo</span> <span style="color: #c20cb9; font-weight: bold;">su</span> postgres</pre></div></div>

<p>Existem duas formas de criar e deletar um usuário, uma através do shell e outra através do cliente postgre.</p>
<p><strong>Via Shell</strong></p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">createuser patrick</pre></div></div>

<p><strong>Via cliente postgres</strong></p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">psql
CREATE USER patrick;</pre></div></div>

<p>As duas opções criam patrick como superusuário.</p>
<p><strong>Exemplos:</strong></p>
<p>Definindo password</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> USER patrick PASSWORD <span style="color: #ff0000;">'123'</span>;</pre></div></div>

<p>Definindo privilégios de superusuário, permissão para criar databases e roles:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> USER patrick SUPERUSER INHERIT CREATEDB CREATEROLE;</pre></div></div>

<p>Mais informações: <a href="http://pgdocptbr.sourceforge.net/pg80/sql-createuser.html">http://pgdocptbr.sourceforge.net/pg80/sql-createuser.html</a>.</p>
<p><strong>Deletar usuário</strong></p>
<p>Via Shell:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">dropuser patrick</pre></div></div>

<p>Via cliente postgres:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">psql
DROP USER patrick;</pre></div></div>

<p>Alterar usuário:</p>
<p>ALTER USER patrick PASSWORD &#8216;teste123&#8242;;</p>
<p>Mais detalhes:<a href=" http://pgdocptbr.sourceforge.net/pg80/sql-alteruser.html"> http://pgdocptbr.sourceforge.net/pg80/sql-alteruser.html</a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.patrickespake.com%2F2009%2F11%2F09%2Finstalacao-do-postgresql%2F&amp;linkname=Instala%C3%A7%C3%A3o%20do%20PostgreSQL"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2009/11/09/instalacao-do-postgresql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails validates_numericality_of para integer ou valores determinados</title>
		<link>http://blog.patrickespake.com/2009/11/06/ruby-on-rails-validates_numericality_of-para-integer-ou-valores-determinados/</link>
		<comments>http://blog.patrickespake.com/2009/11/06/ruby-on-rails-validates_numericality_of-para-integer-ou-valores-determinados/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 20:27:43 +0000</pubDate>
		<dc:creator>patrickespake</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[erro 500]]></category>
		<category><![CDATA[error 500]]></category>
		<category><![CDATA[greater_than_or_equal]]></category>
		<category><![CDATA[integer]]></category>
		<category><![CDATA[less_than_or_equal]]></category>
		<category><![CDATA[naturais]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[validates_numericality_of]]></category>
		<category><![CDATA[valores]]></category>

		<guid isPermaLink="false">http://blog.patrickespake.com/?p=1057</guid>
		<description><![CDATA[Se a sua aplicação Ruby on Rails trabalha com chaves estrangeiras, relacionamentos, é interessante adicionar algumas validações para que o seu sistema não dê erro 500 por uma tentativa mal intecionada de inserção ou atualização do registro.
Isso também é útil quando você quer delimitar uma faixa de valores válidos para o campo.
Geralmente os campos de [...]]]></description>
			<content:encoded><![CDATA[<p>Se a sua aplicação Ruby on Rails trabalha com chaves estrangeiras, relacionamentos, é interessante adicionar algumas validações para que o seu sistema não dê erro 500 por uma tentativa mal intecionada de inserção ou atualização do registro.</p>
<p>Isso também é útil quando você quer delimitar uma faixa de valores válidos para o campo.</p>
<p>Geralmente os campos de chave estrangeira são do tipo integer que pertence ao intervalo de -2147483648 até +2147483647, onde a grande maioria das aplicações trabalha somente com o conjunto dos números N* (naturais sem o zero).</p>
<p>Eu recomendo a seguinte validação no seu model:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Investor <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
  <span style="color:#008000; font-style:italic;"># Para chaves estrangeiras</span>
  validates_numericality_of <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:country_id</span>, <span style="color:#ff3333; font-weight:bold;">:gender_id</span>, <span style="color:#ff3333; font-weight:bold;">:civil_position_id</span><span style="color:#006600; font-weight:bold;">&#93;</span>, <span style="color:#ff3333; font-weight:bold;">:greater_than_or_equal_to</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">1</span>, <span style="color:#ff3333; font-weight:bold;">:less_than_or_equal_to</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">2147483647</span>
  <span style="color:#008000; font-style:italic;"># Para faixa de valor definida</span>
  validates_numericality_of <span style="color:#ff3333; font-weight:bold;">:number_of_dependents</span>, <span style="color:#ff3333; font-weight:bold;">:allow_nil</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span>, <span style="color:#ff3333; font-weight:bold;">:greater_than_or_equal_to</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">0</span>, <span style="color:#ff3333; font-weight:bold;">:less_than_or_equal_to</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">9999</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Desta forma para chaves estrangeiras são apenas aceitos valores de 1 até 2147483647.</p>
<p>Já para a faixa de valor definida você mesmo deve definir, conforme a sua necessidade, no caso do exemplo acima de 0 até 9999.</p>
<p>Se você gostou desse texto e acha que ajudou você, me recomende: <a href="http://www.workingwithrails.com/recommendation/new/person/15479-patrick-espake"><img src="http://workingwithrails.com/images/tools/compact-small-button.jpg" alt="Recommend Me" /></a>.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fblog.patrickespake.com%2F2009%2F11%2F06%2Fruby-on-rails-validates_numericality_of-para-integer-ou-valores-determinados%2F&amp;linkname=Ruby%20on%20Rails%20validates_numericality_of%20para%20integer%20ou%20valores%20determinados"><img src="http://blog.patrickespake.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.patrickespake.com/2009/11/06/ruby-on-rails-validates_numericality_of-para-integer-ou-valores-determinados/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
