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

<channel>
	<title>MongoDB &#8211; WiredPrairie</title>
	<atom:link href="blog/archives/tag/mongodb/feed" rel="self" type="application/rss+xml" />
	<link>/blog</link>
	<description>Yet another tech blog.</description>
	<lastBuildDate>Wed, 29 Jun 2022 15:35:18 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0</generator>
<site xmlns="com-wordpress:feed-additions:1">193486638</site>	<item>
		<title>Simple example of using MongoMapper with Ruby</title>
		<link>/blog/index.php/archives/1965</link>
		
		<dc:creator><![CDATA[Aaron]]></dc:creator>
		<pubDate>Fri, 25 Oct 2013 01:39:08 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Ruby]]></category>
		<guid isPermaLink="false">/blog/?p=1965</guid>

					<description><![CDATA[The MongoMapper web site is really lacking on even simple examples, especially those that don’t use Rails. So, here’s a simple example that might help someone. From the Gemfile: source 'https://rubygems.org/'gem 'mongo_mapper' And then the application: require 'mongo_mapper'# jam it into the database &#34;mm&#34;MongoMapper.database = &#34;mm&#34;class App def create_user user = User.new(:name =&#62; 'Johnny') puts [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>The <a href="http://mongomapper.com/" target="_blank">MongoMapper</a> web site is really lacking on even simple examples, especially those that don’t use Rails. So, here’s a simple example that might help someone. </p>
<p>From the Gemfile:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="border-top-style: none; overflow: visible; font-size: 8pt; font-family: &#39;Courier New&#39;, courier, monospace; width: 100%; border-bottom-style: none; color: black; padding-bottom: 0px; direction: ltr; text-align: left; padding-top: 0px; border-right-style: none; padding-left: 0px; margin: 0em; border-left-style: none; line-height: 12pt; padding-right: 0px; background-color: #f4f4f4">source <span style="color: #006080">'https://rubygems.org/'</span><br /><br />gem <span style="color: #006080">'mongo_mapper'</span><br /></pre>
<p></div>
<p>And then the application:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="border-top-style: none; overflow: visible; font-size: 8pt; font-family: &#39;Courier New&#39;, courier, monospace; width: 100%; border-bottom-style: none; color: black; padding-bottom: 0px; direction: ltr; text-align: left; padding-top: 0px; border-right-style: none; padding-left: 0px; margin: 0em; border-left-style: none; line-height: 12pt; padding-right: 0px; background-color: #f4f4f4">require <span style="color: #006080">'mongo_mapper'</span><br /><br /><br /># jam it <span style="color: #0000ff">into</span> the <span style="color: #0000ff">database</span> &quot;mm&quot;<font color="#9e7c7c"><br /></font>MongoMapper.<span style="color: #0000ff">database</span> = &quot;mm&quot;<br /><br /><span style="color: #0000ff">class</span> App<br /><br />  def create_user<br />    <span style="color: #0000ff">user</span> = <span style="color: #0000ff">User</span>.<span style="color: #0000ff">new</span>(:name =&gt; <span style="color: #006080">'Johnny'</span>)<br />    puts &quot;<span style="color: #0000ff">user</span> created&quot;<br />    <span style="color: #0000ff">user</span>.<span style="color: #0000ff">save</span>!<br />  <span style="color: #0000ff">end</span><br /><br />  def find_user<br />    query = <span style="color: #0000ff">User</span>.<span style="color: #0000ff">where</span>(:name =&gt; <span style="color: #006080">'Johnny'</span>)<br />    <span style="color: #0000ff">user</span> = query.<span style="color: #0000ff">first</span>  # just the <span style="color: #0000ff">first</span><br />    <span style="color: #0000ff">if</span> <span style="color: #0000ff">not</span> <span style="color: #0000ff">user</span>.nil?<br />      puts <span style="color: #0000ff">user</span>.id<br />    <span style="color: #0000ff">end</span><br />  <span style="color: #0000ff">end</span><br /><br />  def delete_user<br />    query = <span style="color: #0000ff">User</span>.<span style="color: #0000ff">where</span>(:name =&gt; <span style="color: #006080">'Johnny'</span>)<br />    <span style="color: #0000ff">user</span> = query.<span style="color: #0000ff">first</span>  # just the <span style="color: #0000ff">first</span><br /><br />    <span style="color: #0000ff">user</span>.<span style="color: #0000ff">destroy</span><br />  <span style="color: #0000ff">end</span><br /><span style="color: #0000ff">end</span><br /><br /><br /><span style="color: #0000ff">class</span> <span style="color: #0000ff">User</span><br />  <span style="color: #0000ff">include</span> MongoMapper::Document<br />  <span style="color: #0000ff">key</span> :name,        String<br />  timestamps!<br /><span style="color: #0000ff">end</span><br /><br />app = App.<span style="color: #0000ff">new</span>()<br />app.create_user<br />app.find_user<br />app.delete_user</pre>
<p></div>
<p>The code does a few things:</p>
<ol>
<li>Creates a new user with a single field called <strong>name.</strong></li>
<li>Finds the user using the <strong>where</strong> function</li>
<li>Removes (destroys/deletes) the user</li>
</ol>
<p>The key things to note are that the <strong>where </strong>function returns a query and not the actual results. The results are fetched on demand. This is very similar to the extension methods and LINQ in .NET as those functions build a query that executed only when the results are first requested. </p>
<p>The same thing is true of MongoMapper in this case. The results are not returned until the <strong>first</strong> function is called. Alternatively, <strong>all</strong> or <strong>last </strong>could have been used. <strong>all</strong> of course returning a list of results that could be iterated in a loop.</p>
<p>If there were no results, the result of calling <strong>first</strong> in this example would be that the <strong>user</strong> variable would be <strong>nil. </strong></p>
<p><em>The <strong>delete_user </strong>function above has absolutely no error checking. </em></p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1965</post-id>	</item>
		<item>
		<title>Mongoose plugin runs for every new Schema</title>
		<link>/blog/index.php/archives/1928</link>
		
		<dc:creator><![CDATA[Aaron]]></dc:creator>
		<pubDate>Mon, 26 Aug 2013 12:44:10 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Mongoose]]></category>
		<guid isPermaLink="false">/blog/?p=1928</guid>

					<description><![CDATA[If you want to consistently apply changes to every Schema in Mongoose, it’s simple. Below is an example. var mongoose = require('mongoose'); var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}"); mongoose.plugin(function(schema, opts) { schema.statics.isObjectId = function(id) { if(id) { return checkForHexRegExp.test(id); } return false; }; }); var AnimalSchema = mongoose.Schema({ name: String }); var Animal = mongoose.model("Animal", AnimalSchema); [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>If you want to consistently apply changes to every <a href="http://mongoosejs.com/docs/guide.html" target="_blank" rel="noopener">Schema</a> in <a href="http://mongoosejs.com/index.html" target="_blank" rel="noopener">Mongoose</a>, it’s simple. Below is an example.</p>



<pre class="wp-block-preformatted"><span class="kwrd">var</span> mongoose = require(<span class="str">'mongoose'</span>);

<span class="kwrd">var</span> checkForHexRegExp = <span class="kwrd">new</span> RegExp(<span class="str">"^[0-9a-fA-F]{24}</span>");
mongoose.plugin(<span class="kwrd">function</span>(schema, opts) { 
    schema.statics.isObjectId = <span class="kwrd">function</span>(id) { 
        <span class="kwrd">if</span>(id) { 
            <span class="kwrd">return</span> checkForHexRegExp.test(id); 
        } 
        <span class="kwrd">return</span> <span class="kwrd">false</span>; 
    }; 
}); 
<span class="kwrd">var</span> AnimalSchema = mongoose.Schema({ name: String }); 
<span class="kwrd">var</span> Animal = mongoose.model(<span class="str">"Animal"</span>, AnimalSchema); <span class="kwrd">if</span>(Animal.isObjectId(<span class="str">"521b4891039857e07aae695a"</span>)) { 
    <span class="kwrd">var</span> animal = <span class="kwrd">new</span> Animal(); <span class="rem">// something more interesting here ...</span> 
}</pre>



<p>The code above uses the <strong>plugin</strong> function on the global mongoose object to add a new plugin. When you add a plugin using that technique, it runs for every schema that is constructed.</p>



<p>So, in this case, I’ve added a static function to every Schema called <strong>isObjectId</strong> which uses a simple regular expression (<a href="https://github.com/mongodb/js-bson/blob/master/lib/bson/objectid.js#L16" target="_blank" rel="noopener">liberally borrowed</a> straight from the bson ObjectId source code) to test whether a string looks like a valid ObjectId (in fact, a 24 character HEX string).</p>



<p>Now, as new models are created (<strong>mongoose.model)</strong>, the Schema is first passed to any defined plugins. The plugin adds the new function <strong>isObjectId</strong>. As you can see, the new <strong>Model</strong> has a static method called <strong>isObjectId</strong>.</p>



<p>The plugin will not affect any Schemas/Models that were defined before the plugin was added.</p>



<p>Using this technique, you could add standardized fields, indexes, etc. without repeating the same code to all Schemas. Of course, you can also use the <strong>plugin</strong> method defined on a Schema to selectively add functionality.</p>



<pre class="wp-block-preformatted"><span class="kwrd">var</span> isObjectIdPlugin = <span class="kwrd">function</span>(schema, opts) {
    schema.statics.isObjectId = <span class="kwrd">function</span>(id) {
        <span class="kwrd">if</span>(id) {
            <span class="kwrd">return</span> checkForHexRegExp.test(id);
        }
        <span class="kwrd">return</span> <span class="kwrd">false</span>;
    };
};


<span class="kwrd">var</span> AnimalSchema = mongoose.Schema({
    name: String
});

AnimalSchema.plugin(isObjectIdPlugin);

<span class="kwrd">var</span> Animal = mongoose.model(<span class="str">"Animal"</span>, AnimalSchema);

<span class="kwrd">if</span>(Animal.isObjectId(<span class="str">"521b4891039857e07aae695a"</span>)) {
    <span class="kwrd">var</span> animal = <span class="kwrd">new</span> Animal();
    <span class="rem">// something more interesting here ...</span>
}</pre>



<p></p>



<p>Above, the code applies the plugin to only the AnimalSchema using the <strong>plugin</strong> method.</p>



<p><em>Of course, adding the same method statically may not be very useful – instead it probably belongs somewhere in a utility class (and really it’s too bad it’s not just exposed directly by the BSON ObjectId class).</em></p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1928</post-id>	</item>
		<item>
		<title>Using $inc to increment a field in a sub-document in an array and a field in main document</title>
		<link>/blog/index.php/archives/1895</link>
		
		<dc:creator><![CDATA[Aaron]]></dc:creator>
		<pubDate>Sun, 14 Jul 2013 15:32:29 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[MongoDB]]></category>
		<guid isPermaLink="false">/blog/?p=1895</guid>

					<description><![CDATA[(Blog post inspired by question I answered on StackOverflow) Lets say you have a schema in MongoDB that looks something like this: { '_id' : 'star_wars', 'count' : 1234, 'spellings' : [ { spelling: 'Star wars', total: 10}, { spelling: 'Star Wars', total : 15}, { spelling: 'sTaR WaRs', total : 5} ] } Atomically, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>(Blog post inspired by <a href="http://stackoverflow.com/questions/17639651/mongodb-aggregation-framework" target="_blank" rel="noopener">question I answered</a> on StackOverflow)</p>
<p>Lets say you have a schema in MongoDB that looks something like this:</p>
<pre class="csharpcode">{
  <span class="str">'_id'</span> : <span class="str">'star_wars'</span>,
  <span class="str">'count'</span> : 1234,
  <span class="str">'spellings'</span> : [ 
    { spelling: <span class="str">'Star wars'</span>, total: 10}, 
    { spelling: <span class="str">'Star Wars'</span>, total : 15}, 
    { spelling: <span class="str">'sTaR WaRs'</span>, total : 5} ]
}</pre>
<p>Atomically, you’d like to update two fields at one time, the total for a particular spelling which is in a sub document in an array, and the overall count field.</p>
<p>The way to handle this is to take advantage of the <a href="http://docs.mongodb.org/manual/reference/operator/positional/" target="_blank" rel="noopener">positional array operator</a> and the <strong><a href="http://docs.mongodb.org/manual/reference/operator/inc/" target="_blank" rel="noopener">$inc</a></strong> operator.</p>
<p>Starting with just updating the count, that’s easy:</p>
<pre class="csharpcode">db.movies.update( 
    {_id: <span class="str">"star_wars"</span>}, 
    { $inc : { <span class="str">'count'</span> : 1 }}
)</pre>
<p>The query matches on the document with the <strong>_id</strong> of <strong>star_wars</strong>, and increments the <strong>count </strong>by 1.</p>
<p>The positional operator is where the mongo-magic comes into play here. If you wanted to just update a single sub-document in the array, add it to the query. First, we’ll try finding the right document:</p>
<pre class="csharpcode">db.movies.find( {
    _id: <span class="str">"star_wars"</span>, 
    <span class="str">'spellings.spelling'</span> : <span class="str">"Star Wars"</span> }
)</pre>
<p>That matches the right document, but also returns all of the elements of the array.</p>
<p>But, wait, there’s more! When you match on an element/document of an array, the position of the match is remembered and can be used in the update phase. You do that using the positional operator. Using the document above, you’ll use this: <strong>spellings.$.total</strong>. If you knew the specific index into the array, the <strong>$</strong> could have been replaced with the zero-based index number (like a <strong>1</strong> for example in this case: <strong>spellings.1.total</strong>).</p>
<p>Putting it all together then results in a slick and simple way of incrementing multiple fields in a document.</p>
<pre class="csharpcode">db.movies.update( 
    {_id: <span class="str">"star_wars"</span>,
     <span class="str">'spellings.spelling'</span> : <span class="str">"Star Wars"</span> },
    { $inc : 
        { <span class="str">'spellings.$.total'</span> : 1, 
        <span class="str">'count'</span> : 1 }})</pre>
<p>Results:</p>
<pre class="csharpcode">{
  <span class="str">'_id'</span> : <span class="str">'star_wars'</span>,
  <span class="str">'count'</span> : 1235,
  <span class="str">'spellings'</span> : [ 
    { spelling: <span class="str">'Star wars'</span>, total: 10}, 
    { spelling: <span class="str">'Star Wars'</span>, total : 16}, 
    { spelling: <span class="str">'sTaR WaRs'</span>, total : 5} ]
}</pre>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1895</post-id>	</item>
		<item>
		<title>Finding duplicates in MongoDB via the shell</title>
		<link>/blog/index.php/archives/1857</link>
		
		<dc:creator><![CDATA[Aaron]]></dc:creator>
		<pubDate>Sun, 10 Mar 2013 18:45:41 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[MongoDB]]></category>
		<guid isPermaLink="false">/blog/?p=1857</guid>

					<description><![CDATA[I thought this was an interesting question to answer on StackOverflow (summarized here): I’m trying to create an index, but an error is returned that duplicates exist for the field I want to index. What should I do? I answered with one possibility. The summary is that you can use the power of MongoDB’s aggregation [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I thought this was an interesting question to answer on StackOverflow (summarized here):</p>
<blockquote>
<p>I’m trying to create an index, but an error is returned that duplicates exist for the field I want to index. What should I do?</p>
</blockquote>
<p>I answered with <a href="http://stackoverflow.com/a/15323839/95190">one</a> possibility.</p>
<p>The summary is that you can use the power of MongoDB’s <a href="http://docs.mongodb.org/manual/applications/aggregation/">aggregation</a> framework to search and return the duplicates. It’s really quite slick.</p>
<p>For example, in the question, <strong>Wall </strong>documents had a field called <strong>event_time</strong>. Here’s one approach:</p>
<pre><code>db.Wall.aggregate([
       {$group : { _id: &quot;$event_time&quot; ,  count : { $sum: 1}}},
       {$match : { count : { $gt : 1 } }} ])</code></pre>
<p>The trick is to use the $group pipeline operator to select and count each unique event_time. Then, match on only those groups that contained more than one match. </p>
<p>While it’s not necessarily as readable as the equivalent SQL statement potentially, it’s still easy to read. The only really odd thing is the mapping of the <strong>event_time</strong> into the <strong>_id</strong>. As all documents pass through the pipeline, the <strong>event_time</strong> is used as the new aggregate document key. The $ sign is used as the field reference to a property of the document in the pipeline (a <strong>Wall</strong> document). Remember that the <strong>_id</strong> field of a MongoDB document must be unique (and this is how the $group pipeline operator does its magic).</p>
<p>So, if the following <strong>event_time</strong>s were in the documents:</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="400"><strong>event_time</strong></td>
</tr>
<tr>
<td valign="top" width="400">4:00am</td>
</tr>
<tr>
<td valign="top" width="400">5:00am</td>
</tr>
<tr>
<td valign="top" width="400">4:00am</td>
</tr>
<tr>
<td valign="top" width="400">6:00pm</td>
</tr>
<tr>
<td valign="top" width="400">7:00a</td>
</tr>
</tbody>
</table>
<p>It would results in a aggregate set of documents:</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="200"><strong>_id</strong></td>
<td valign="top" width="200"><strong>count</strong></td>
</tr>
<tr>
<td valign="top" width="200">4:00am</td>
<td valign="top" width="200">2</td>
</tr>
<tr>
<td valign="top" width="200">5:00am</td>
<td valign="top" width="200">1</td>
</tr>
<tr>
<td valign="top" width="200">6:00pm</td>
<td valign="top" width="200">1</td>
</tr>
<tr>
<td valign="top" width="200">7:00am</td>
<td valign="top" width="200">1</td>
</tr>
</tbody>
</table>
<p>Notice how the _id is the <strong>event_time. </strong>The aggregate results would look like this:</p>
<pre class="csharpcode">{
        <span class="str">&quot;result&quot;</span> : [
                {
                        <span class="str">&quot;_id&quot;</span> : <span class="str">&quot;4:00am&quot;</span>,
                        <span class="str">&quot;count&quot;</span> : 2
                }
        ],
        <span class="str">&quot;ok&quot;</span> : 1
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1857</post-id>	</item>
		<item>
		<title>How to rewrite a MongoDB C# LINQ with a Projection Requirement using a MongoCursor</title>
		<link>/blog/index.php/archives/1835</link>
		
		<dc:creator><![CDATA[Aaron]]></dc:creator>
		<pubDate>Sat, 26 Jan 2013 22:56:00 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[MongoDB]]></category>
		<guid isPermaLink="false">/blog/?p=1835</guid>

					<description><![CDATA[The LINQ Provider for MongoDB does not currently take into account data projections efficiently when returning data. This could mean that you’re unnecessarily returning more data from the database than is needed. So, I’m going to show you the pattern I applied as a replacement for the LINQ queries when I need to use a [&#8230;]]]></description>
										<content:encoded><![CDATA[<p align="left">The LINQ Provider for MongoDB does not <a href="https://jira.mongodb.org/browse/CSHARP-456">currently</a> take into account data projections efficiently when returning data. This could mean that you’re unnecessarily returning more data from the database than is needed. </p>
<p>So, I’m going to show you the pattern I applied as a replacement for the LINQ queries when I need to use a projection.</p>
<p>Given the following simple LINQ statement:</p>
<pre class="csharpcode">var query = 
    (from r <span class="kwrd">in</span> DataLayer.Database
         .GetCollection&lt;Research&gt;()
         .AsQueryable&lt;Research&gt;()
        <span class="kwrd">where</span> !r.Deleted
        select <span class="kwrd">new</span>
        {
            Id = r.Id,
            Title = r.Title,
            Created = r.Created
        }).Skip(PageSize * page).Take(PageSize);</pre>
<p><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>it can be converted to a MongoCursor style search like this:</p>
<pre class="csharpcode">var cursor = DataLayer.Database.GetCollection&lt;Research&gt;()
    .FindAs&lt;Research&gt;(Query&lt;Research&gt;.NE(r =&gt; r.Deleted, <span class="kwrd">true</span>))
        .SetFields(
            Fields&lt;Research&gt;.Include(
                r =&gt; r.Id, 
                r =&gt; r.Title, 
                r =&gt; r.Created))
        .SetLimit(PageSize)
        .SetSkip(PageSize * page);           </pre>
<p><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>I’ve attempted to format it in a similar way mostly for my own sanity. As you see, both queries first get access to the database collection. But, instead of using <strong>AsQueryable&lt;T&gt;</strong>, you’ll use the <strong>FindAs&lt;T&gt;</strong> method. The query is more verbose in the second example, although not overly so. I chose to keep it strongly typed by using the generic version <strong>Query&lt;Research&gt;</strong>. By doing so, it meant that I could use an Expression to set the field/property that was being queried, rather than rely on a string (I could have just passed “Deleted” as a string in the code). </p>
<p>By strongly typing the parameters in this way, it meant that the compile process can catch things like type mismatches (verifying that the value being compared is a Boolean for example as is the Deleted property).</p>
<p>Secondly, and this addresses the requirement of a <a href="http://docs.mongodb.org/manual/core/read-operations/#result-projections">result projection</a>, I’ve included just those fields that are required by the UI rather than all of the fields in the document. One of the fields is potentially quite long (up to 1MB of text), and in this case, unnecessary in a summary list display in my web application. Here, I used the <strong>SetFields </strong>method of the MongoCursor.</p>
<p>The C# driver includes a static class called <strong>Fields</strong> (in a generic and non-generic form) which can be used to express the set of fields to be included/excluded. I’ll point out that there is an option to just pass in a list of strings to <strong>SetFields</strong>, but it’s not strongly typed. So again, no compile-time checking that I’ve got the property names correct. I’m going for safety here, so I chose the strongly-typed generic implementation of <strong>Fields&lt;Research&gt;</strong>. Then, using the <strong>Expression</strong> syntax again, I’ve selected the fields I needed as a parameter list.</p>
<p>Finally, I added some code to limit the result size and set the skip equivalent to the original LINQ query. </p>
<p>There are a number of other Query methods that you can use to build more complex operations.</p>
<p>For example:</p>
<pre class="csharpcode">var q = Query.And(
    Query&lt;Research&gt;.Exists(r =&gt; r.Title), 
    Query&lt;Research&gt;.Matches(
        r =&gt; r.Title, BsonRegularExpression.Create(<span class="kwrd">new</span> Regex(<span class="str">&quot;^R&quot;</span>))));</pre>
<p><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>The above maps to the following MongoDB query:</p>
<pre class="csharpcode">{ <span class="str">&quot;$and&quot;</span> : [{ <span class="str">&quot;Title&quot;</span> : { <span class="str">&quot;$exists&quot;</span> : <span class="kwrd">true</span> } }, { <span class="str">&quot;Title&quot;</span> : /^R/ }] }</pre>
<p>Title field exists and the Title field starts with an uppercase “R”.</p>
<p>While the Query style syntax is more verbose than the equivalent LINQ statement, the result still is expressive and very readable and maintainable.</p>
<p>FYI: If there’s an index on Title, then the /^R/ syntax returns the results the most <a href="http://docs.mongodb.org/manual/reference/operator/regex/#_S_regex">efficiently</a> in MongoDB (as it stops searching after the first character).</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1835</post-id>	</item>
		<item>
		<title>How to view the MongoDB Query when using the C# LINQ Provider</title>
		<link>/blog/index.php/archives/1833</link>
		
		<dc:creator><![CDATA[Aaron]]></dc:creator>
		<pubDate>Sat, 26 Jan 2013 17:04:46 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[IQueryable]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[MongoDB]]></category>
		<guid isPermaLink="false">/blog/?p=1833</guid>

					<description><![CDATA[If you’re using the Official MongoDB C# Driver from 10gen, you may want to occasionally verify that the generated query matches your LINQ query (or at least that it’s building something efficient). Take for example this query: var query = (from r in DataLayer.Database.GetCollection&#60;Research&#62;().AsQueryable&#60;Research&#62;() where !r.Deleted select new { Id = r.Id, Title = r.Title, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>If you’re using the <a href="http://www.mongodb.org/display/DOCS/CSharp+Language+Center">Official MongoDB C# Driver</a> from 10gen, you may want to occasionally verify that the generated query matches your LINQ query (or at least that it’s building something efficient). </p>
<p>Take for example this query:</p>
<pre class="csharpcode">var query = 
    (from r <span class="kwrd">in</span> DataLayer.Database.GetCollection&lt;Research&gt;().AsQueryable&lt;Research&gt;()
        <span class="kwrd">where</span> !r.Deleted
        select <span class="kwrd">new</span>
        {
            Id = r.Id,
            Title = r.Title,
            Created = r.Created
        }).Skip(PageSize * page).Take(PageSize);

query.DebugWriteMongoQueryText();</pre>
<p><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>I wanted to verify that the query was checking the Deleted property, and see if the projection was considered as part of the query, so a few lines of code later …</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> ToMongoQueryText&lt;TQueryable&gt;(<span class="kwrd">this</span> IQueryable&lt;TQueryable&gt; query)
{
    <span class="kwrd">return</span> (query <span class="kwrd">as</span> MongoQueryable&lt;TQueryable&gt;).GetMongoQuery().ToString();            
}

[Conditional(<span class="str">&quot;DEBUG&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> DebugWriteMongoQueryText&lt;TQuerable&gt;(<span class="kwrd">this</span> IQueryable&lt;TQuerable&gt; query)
{
    Debug.WriteLine(<span class="str">&quot;QUERY: &quot;</span> + query.ToMongoQueryText());
}</pre>
<p><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>I added two extension methods to IQueryable. As the return type for the query in my sample is actually an anonymous type, it wasn’t something I could easily type in the Immediate Window in Visual Studio for example. </p>
<p><a href="blog/wpcontent/uploads/2013/01/image1.png"><img loading="lazy" title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: none; padding-top: 0px; padding-left: 0px; margin-left: auto; border-left: 0px; display: block; padding-right: 0px; margin-right: auto" border="0" alt="&lt;&gt;f__AnonymousType2&lt;string,string,System.DateTime&gt;" src="blog/wpcontent/uploads/2013/01/image_thumb1.png" width="514" height="95" /></a></p>
<p>No thanks&#160; &lt;&gt;f__AnonymousType2&lt;string,string,System.DateTime&gt;.</p>
<p>I added the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute(v=vs.110).aspx">Conditional</a> Attribute so that the code would only execute in a Debug build of my application.</p>
<pre class="csharpcode">query.DebugWriteMongoQueryText();</pre>
<p>The output of the query above was:</p>
<pre class="csharpcode">QUERY: { <span class="str">&quot;Deleted&quot;</span> : { <span class="str">&quot;$ne&quot;</span> : <span class="kwrd">true</span> } }</pre>
<p><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>As you’ll see, the anonymous projection wasn’t considered. Unfortunately, that’s a <a href="https://jira.mongodb.org/browse/CSHARP-456">known issue</a> with the current driver. This mattered in my above example, as some of the fields could contain a large amount of data that wasn’t needed by the current display. </p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1833</post-id>	</item>
	</channel>
</rss>
