<?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>Mongo - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/mongo/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Sun, 12 Nov 2023 17:57:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://thecodebuzz.com/wp-content/uploads/2022/11/cropped-android-chrome-512x512-1-1-51x51.jpg</url>
	<title>Mongo - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>MongoDB &#8211; Get the last N records OR most recent records</title>
		<link>https://thecodebuzz.com/get-the-last-n-records-in-mongodb-get-most-recent-records-mongodb/</link>
					<comments>https://thecodebuzz.com/get-the-last-n-records-in-mongodb-get-most-recent-records-mongodb/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 08 Dec 2022 04:37:00 +0000</pubDate>
				<category><![CDATA[Mongo]]></category>
		<category><![CDATA[find last record in mongodb compass]]></category>
		<category><![CDATA[mongodb c# get last record]]></category>
		<category><![CDATA[mongodb get last updated document]]></category>
		<category><![CDATA[mongodb get latest record by _id]]></category>
		<category><![CDATA[mongodb get latest record by date]]></category>
		<category><![CDATA[mongodb get latest record by group]]></category>
		<category><![CDATA[mongodb last]]></category>
		<category><![CDATA[python mongodb get last record]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=25007</guid>

					<description><![CDATA[<p>MongoDB &#8211; Get the last N records OR most recent records Today in this article, we will learn to perform MongoDB &#8211; Get the last N records OR most recent records. There are easy approaches to achieving the last N records or most records in the mongo document. We will cover a few approaches to [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/get-the-last-n-records-in-mongodb-get-most-recent-records-mongodb/">MongoDB – Get the last N records OR most recent records</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">MongoDB &#8211; Get the last N records OR most recent records</h1>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2022/12/how-to-get-the-last-n-records-in-mongodb-mongo-shell-1024x310.jpg" alt="MongoDB - Get the last N records " class="wp-image-25017"/></figure>



<p>Today in this article, we will learn to perform MongoDB &#8211; Get the last N records OR most recent records. There are easy approaches to achieving the last N records or most records in the mongo document.</p>



<p></p>



<p></p>



<p>We will cover a few approaches to Get the last N records OR most recent records.</p>



<p></p>



<p>Overall, We will cover the below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-command">Command:</a><ul><li><a href="#aioseo-command-to-get-first-n-element-based-on-sort">Command to get the first N element in MongoDB</a></li></ul></li><li><a href="#aioseo-example">Example :</a><ul><li><a href="#aioseo-get-first-100-records-in-mongodb">Get the last 2 records in MongoDB</a></li><li><a href="#aioseo-get-first-50-records-in-mongodb">Get the last 50 records in MongoDB</a></li><li><a href="#aioseo-get-first-100-records-in-mongodb">Get the last 100 records in MongoDB</a></li></ul></li><li><a href="#aioseo-command-to-get-recent-record-in-mongodb">Command to get the recent record in MongoDB</a></li><li><a href="#aioseo-command">Command:</a><ul><li><a href="#aioseo-command-to-get-first-n-element-based-on-sort">Command to get the most recent records in MongoDB</a></li></ul></li></ul></div>



<p></p>



<p></p>



<p>I have below <strong><em>Mongo Collection </em></strong>where my fields are defined as below. </p>



<p></p>



<p></p>



<p>I have a field name called &#8220;<strong><em>UserID</em></strong>&#8221; which is of type &#8220;<strong><em>Int</em></strong>&#8220;. I want to use this field to query first &#8220;N&#8221; element from MongoDB.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-command"><strong>Command</strong>:</h2>



<p></p>



<h3 class="wp-block-heading" id="aioseo-command-to-get-first-n-element-based-on-sort">Command to get the first N element in MongoDB</h3>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.&lt;Collection&gt;.find().sort({&lt;field&gt;<strong>:1</strong>}).limit(N)</pre>



<p></p>



<p>The above query will give records based on <strong>Ascending </strong>order of field value.</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size"> db.&lt;Collection&gt;.find().sort({&lt;field&gt;:<strong>-1</strong>}).limit(N) </pre>



<p></p>



<p>Similarly, the above query will give records based on <strong>descending </strong>order of field value.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-example">Example :</h2>



<p> </p>



<h3 class="wp-block-heading" id="aioseo-get-first-100-records-in-mongodb">Get the last 2 records in MongoDB</h3>



<p></p>



<p><strong>Ascending </strong>order,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.Books.find().sort({UserId:1}).limit(<strong>2</strong>)
</pre>



<p>OR</p>



<p></p>



<p><strong>Descending </strong>Order,</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.Books.find().sort({UserId:-1}).limit(<strong>2</strong>)  </pre>



<p></p>



<figure class="wp-block-image size-large"><a href="https://www.thecodebuzz.com/gettimestamp-mongodb-using-objectid-mongoshell-cli-atlas/" target="_blank" rel="noopener"><img decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2022/12/how-to-get-the-last-n-records-in-mongodb-1024x113.jpg" alt="" class="wp-image-25013"/></a></figure>



<pre class="wp-block-preformatted has-medium-font-size">db.Books.find().sort({UserId:1}).limit(2)

{ "_id" : ObjectId("62c5dd1902514a766441e2ee"), "UserId" : 555, "Books" : [ { "book_name" : "book_name1", "price" : "88", "category" : [ { "key" : "Test1", "value" : 123 } ] }, { "book_name" : "book_name2", "price" : "50", "category" : [ { "key" : "test2-1", "value" : null }, { "key" : "test4", "value" : null } ] } ], "value" : null }

{ "_id" : ObjectId("6382cfa8c592b1532c8d5bcb"), "UserId" : 934, "DateAdded" : ISODate("2022-01-01T05:00:00Z"), "Books" : [ { "book_name" : "book_name1", "price" : null, "category" : [ { "key" : "Test1", "value" : null } ] }, { "book_name" : "book_name2", "price" : "50", "category" : [ { "key" : "test
</pre>



<p></p>



<h3 class="wp-block-heading" id="aioseo-get-first-50-records-in-mongodb">Get the last 50 records in MongoDB </h3>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.Books.find().sort({UserId:-1}).limit(<strong>50</strong>)</pre>



<p></p>



<h3 class="wp-block-heading" id="aioseo-get-first-100-records-in-mongodb">Get the last 100 records in MongoDB</h3>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size"> db.Books.find().sort({UserId:-1}).limit(<strong>100</strong>) </pre>



<p></p>



<h2 class="wp-block-heading" id="aioseo-command-to-get-recent-record-in-mongodb">Command to get the recent record in MongoDB </h2>



<p></p>



<h2 class="wp-block-heading" id="aioseo-command"><strong>Command</strong>:</h2>



<p></p>



<h3 class="wp-block-heading" id="aioseo-command-to-get-first-n-element-based-on-sort">Command to get the most recent records in MongoDB</h3>



<p></p>



<p>If you have a date field already in the MongoDB document then you can sort the most recent documents based on dates.</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.&lt;Collection&gt;.find().sort({<strong>&lt;DateField&gt;</strong>:-1}).limit(N)
</pre>



<p>OR </p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size"> db.&lt;Collection&gt;.find().sort({<strong>_id</strong>:-1}).limit(N) </pre>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>If your <strong>Mongo </strong>records use default <strong>ObjectID</strong>, then this <strong>_id </strong>will have a default insertion time that is unique and can be used to get records.</p></blockquote>



<p></p>



<p><strong>Example</strong></p>



<p></p>



<pre id="block-a5125798-f594-487f-8eee-0f9d0edf9f86" class="wp-block-preformatted has-medium-font-size">db.Books.find().sort({DateAdded:1}).limit(5)</pre>



<p>OR</p>



<p></p>



<pre id="aioseo-db-books-find-sortdateadded1-limit5" class="wp-block-preformatted has-medium-font-size"> db.Books.find().sort({_id : -1}).limit(5) </pre>



<p></p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2022/12/how-to-get-most-recent-records-in-mongodb-1024x145.jpg" alt="mongodb get last inserted document,
mongodb get last record,
mongodb get latest record by date,
mongodb get latest record by group,
mongodb get latest record by id,
python mongodb get last record,
mongodb find reverse order,
find last record in mongodb compass," class="wp-image-25015"/></figure>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>db.Books.find().sort({DateAdded:1}).limit(5)</p><p><br>{ &#8220;_id&#8221; : ObjectId(&#8220;62c5dd1902514a766441e2ee&#8221;), &#8220;UserId&#8221; : 555, &#8220;Books&#8221; : [ { &#8220;book_name&#8221; : &#8220;book_name1&#8221;, &#8220;price&#8221; : &#8220;88&#8221;, &#8220;category&#8221; : [ { &#8220;key&#8221; : &#8220;Test1&#8221;, &#8220;value&#8221; : 123 } ] }, { &#8220;book_name&#8221; : &#8220;book_name2&#8221;, &#8220;price&#8221; : &#8220;50&#8221;, &#8220;category&#8221; : [ { &#8220;key&#8221; : &#8220;test2-1&#8221;, &#8220;value&#8221; : null }, { &#8220;key&#8221; : &#8220;test4&#8221;, &#8220;value&#8221; : null } ] } ], &#8220;value&#8221; : null }<br>{ &#8220;_id&#8221; : ObjectId(&#8220;62c5e3f602514a766441e2ef&#8221;), &#8220;UserId&#8221; : 6777, &#8220;DateAdded&#8221; : ISODate(&#8220;2019-01-01T05:00:00Z&#8221;), &#8220;Books&#8221; : [ { &#8220;book_name&#8221; : &#8220;book_name1&#8221;, &#8220;price&#8221; : null, &#8220;category&#8221; : [ { &#8220;key&#8221; : &#8220;Test1&#8221;, &#8220;value&#8221; : null } ] }, { &#8220;book_name&#8221; : &#8220;book_name2&#8221;, &#8220;price&#8221; : &#8220;50&#8221;, &#8220;category&#8221; : [ { &#8220;key&#8221; : &#8220;test3&#8221;, &#8220;value&#8221; : null }, { &#8220;key&#8221; : &#8220;test4&#8221;, &#8220;value&#8221; : null } ] } ], &#8220;value&#8221; : null }<br>{ &#8220;_id&#8221; : ObjectId(&#8220;6382cfbec592b1532c8d5bcc&#8221;), &#8220;UserId&#8221; : 6777, &#8220;DateAdded&#8221; : ISODate(&#8220;2021-01-01T05:00:00Z&#8221;), &#8220;Books&#8221; : [ { &#8220;book_name&#8221; : &#8220;book_name1&#8221;, &#8220;price&#8221; : null, &#8220;category&#8221; : [ { &#8220;key&#8221; : &#8220;Test1&#8221;, &#8220;value&#8221; : null } ] }, { &#8220;book_name&#8221; : &#8220;book_name2&#8221;, &#8220;price&#8221; : &#8220;50&#8221;, &#8220;category&#8221; : [ { &#8220;key&#8221; : &#8220;test3&#8221;, &#8220;value&#8221; : null }, { &#8220;key&#8221; : &#8220;test4&#8221;, &#8220;value&#8221; : null } ] } ], &#8220;value&#8221; : null }<br>{ &#8220;_id&#8221; : ObjectId(&#8220;6382cfa8c592b1532c8d5bcb&#8221;), &#8220;UserId&#8221; : 934, &#8220;DateAdded&#8221; : ISODate(&#8220;2022-01-01T05:00:00Z&#8221;), &#8220;Books&#8221; : [ { &#8220;book_name&#8221; : &#8220;book_name1&#8221;, &#8220;price&#8221; : null, &#8220;category&#8221; : [ { &#8220;key&#8221; : &#8220;Test1&#8221;, &#8220;value&#8221; : null } ] }, { &#8220;book_name&#8221; : &#8220;book_name2&#8221;, &#8220;price&#8221; : &#8220;50&#8221;, &#8220;category&#8221; : [ { &#8220;key&#8221; : &#8220;test3&#8221;, &#8220;value&#8221; : null }, { &#8220;key&#8221; : &#8220;test4&#8221;, &#8220;value&#8221; : null } ] } ], &#8220;value&#8221; : null }</p></blockquote>



<p></p>



<p>If you don&#8217;t have a Date field, you can still use the inbuilt default date object for getting recent documents.</p>



<p></p>



<p>Please refer to this article for more details, </p>



<p></p>



<ul class="has-medium-font-size wp-block-list"><li><a href="https://www.thecodebuzz.com/query-mongodb-objectid-by-date-mongoshell-compass/" target="_blank" rel="noopener" title="Query MongoDB using ObjectId by Date -MongoShell">Query MongoDB using ObjectId by Date -MongoShell</a></li></ul>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/get-the-last-n-records-in-mongodb-get-most-recent-records-mongodb/">MongoDB – Get the last N records OR most recent records</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/get-the-last-n-records-in-mongodb-get-most-recent-records-mongodb/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>MongoDB Change The Type of a field &#8211;  Guidelines</title>
		<link>https://thecodebuzz.com/mongodb-change-type-of-a-field-convert-string-numeric/</link>
					<comments>https://thecodebuzz.com/mongodb-change-type-of-a-field-convert-string-numeric/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 22 Oct 2022 14:48:00 +0000</pubDate>
				<category><![CDATA[Mongo]]></category>
		<category><![CDATA[convert object to array in mongodb]]></category>
		<category><![CDATA[how to change data type in mongodb compass]]></category>
		<category><![CDATA[mongodb 3.6 convert int to string]]></category>
		<category><![CDATA[mongodb aggregate transform]]></category>
		<category><![CDATA[mongodb change field type]]></category>
		<category><![CDATA[mongodb change field type from double to int]]></category>
		<category><![CDATA[mongodb change field type from string to array]]></category>
		<category><![CDATA[mongodb change field type from string to date]]></category>
		<category><![CDATA[mongodb change field type from string to number]]></category>
		<category><![CDATA[mongodb change field type from string to objectid]]></category>
		<category><![CDATA[mongodb change field type to array]]></category>
		<category><![CDATA[mongodb compass change field type for all documents]]></category>
		<category><![CDATA[mongodb convert field to array]]></category>
		<category><![CDATA[mongodb convert string to array]]></category>
		<category><![CDATA[mongodb force data type]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=24455</guid>

					<description><![CDATA[<p>MongoDB Change The Type of a field &#8211; Guidelines Today in this article, we will learn MongoDB Change The Type of a field. There are multiple approaches to achieving the data type change as explained below, We will cover various 3-4 approaches to perform the datatype change feature. Overall, We will cover the below aspects, [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/mongodb-change-type-of-a-field-convert-string-numeric/">MongoDB Change The Type of a field –  Guidelines</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">MongoDB Change The Type of a field &#8211;  Guidelines</h1>



<figure class="wp-block-image size-large is-resized"><img fetchpriority="high" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-mongo-shell-mongooose-cli-1024x310.jpg" alt="" class="wp-image-24623" width="715" height="216" srcset="https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-mongo-shell-mongooose-cli-1024x310.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-mongo-shell-mongooose-cli-300x91.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-mongo-shell-mongooose-cli-768x232.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-mongo-shell-mongooose-cli-1536x464.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-mongo-shell-mongooose-cli-785x237.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-mongo-shell-mongooose-cli.JPG 1548w" sizes="(max-width: 715px) 100vw, 715px" /></figure>



<p>Today in this article, we will learn MongoDB Change The Type of a field. There are multiple approaches to achieving the data type change as explained below,</p>



<p></p>



<ul class="wp-block-list">
<li>Change data type using Mongo Compass UI or any other UI &#8211;<em><strong>Manual way </strong></em></li>



<li>Change data type in Mongo Using Aggregation Type Expression Operators &#8211; An automated<em> way </em>
<ul class="wp-block-list">
<li>Using Aggregation Operators like <strong>$toInt , $toString </strong></li>



<li>Using Aggregation Operators like  <strong>$convert</strong></li>
</ul>
</li>
</ul>



<p></p>



<p>We will cover various 3-4 approaches to perform the datatype change feature.</p>



<p></p>



<p>Overall, We will cover the below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-change-data-type-using-mongo-compass-ui-or-any-other-ui-manual-way">Change data type using Mongo Compass UI or any other UI -Manual way</a></li><li><a href="#aioseo-change-data-type-in-mongo-using-aggregation-type-expression-operators-automated-way">Change data type in Mongo Using Aggregation Type Expression Operators &#8211; An automated way</a><ul><li><a href="#aioseo-approach-1---remove-the-field-for-all-the-documents-in-the-database">Example &#8211; Convert string to numerical values in MongoDB</a></li><li><a href="#aioseo-how-to-convert-data-type-for-all-documents-in-mongo-db">How to convert data type for all documents in Mongo DB</a></li><li><a href="#aioseo-what-is">What is $toInt</a></li><li><a href="#aioseo-approach-2---remove-the-field-for-all-documents-in-the-mongodb">Example &#8211; Convert a numeric value to a string in MongoDB</a></li><li><a href="#aioseo-what-is-tostring">What is $toString</a></li><li><a href="#aioseo-approach-3---remove-the-field-for-all-documents-in-the-database-using-updatemany">Example &#8211; Convert a NumberLong to a String</a></li></ul></li><li><a href="#aioseo-using-aggregation-operators-like-convert">Using Aggregation Operators like  $convert</a></li></ul></div>



<p></p>



<p>The below approach discussed is very useful when you don&#8217;t want to delete or drop the mongo fields but rather want to change the type of a field.</p>



<p></p>



<p>I have below <strong><em>Mongo Collection </em></strong>where my fields are defined as below. </p>



<p></p>



<p>I have a field name called &#8220;<strong><em>EmpID</em></strong>&#8221; which is of type &#8220;<strong><em>string</em></strong>&#8220;. I want to change this field to &#8220;<strong><em>int</em></strong>&#8221; using MongoShell.</p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-change-data-type-using-mongo-compass-ui-or-any-other-ui-manual-way"><span style="font-size: revert; color: initial;">Change data type using Mongo Compass UI or any other UI &#8211;</span><em style="font-size: revert; color: initial;">Manual way </em> </h2>



<p></p>



<p>One can easily change the data type of a field in the Mongo DB document </p>



<p>In Mongo Atlas click on Edit Document. Here you will get an option to choose the data type,</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="354" src="https://www.thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-Mongo-Compass-UI-1024x354.jpg" alt="MongoDB Change The Type of a field, mongodb change field type from string to date," class="wp-image-24499" srcset="https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-Mongo-Compass-UI-1024x354.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-Mongo-Compass-UI-300x104.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-Mongo-Compass-UI-768x266.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-Mongo-Compass-UI-1536x531.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-Mongo-Compass-UI-2048x709.jpg 2048w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-Mongo-Compass-UI-785x272.jpg 785w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p>As shown above, the manual approach can be used as needed. </p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-change-data-type-in-mongo-using-aggregation-type-expression-operators-automated-way"><span style="font-size: revert; color: initial;">Change data type in Mongo Using Aggregation Type Expression Operators &#8211; An automated</span><em style="font-size: revert; color: initial;"> way</em> </h2>



<p></p>



<p>Please open the <strong><em>command prompt or Mongo shell </em></strong>and log in<em> to your database using a connection string</em>.</p>



<p></p>



<p>We will first login to MongoDB and then switch to using the required database and the collection</p>



<p> </p>



<p><strong>Command Pattern</strong></p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.&lt;collection-name&gt;.update( {}, [ {$set:{ "&lt;field-name&gt;" : {$&lt;field type&gt;: "$&lt;field-name&gt;"}}} ]</pre>



<p></p>



<h3 class="wp-block-heading" id="aioseo-approach-1---remove-the-field-for-all-the-documents-in-the-database">Example &#8211; Convert string to numerical values in MongoDB</h3>



<p></p>



<p></p>



<p><strong>Example </strong></p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.employee.update({}, [ {$set:{ "EmpID" : {$<strong>toInt</strong>: "$EmpID"}}} ], {multi:true})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })</pre>



<p></p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="167" src="https://www.thecodebuzz.com/wp-content/uploads/2022/11/Convert-string-to-numerical-values-in-MongoDB-1024x167.jpg" alt="mongodb change field type from double to int" class="wp-image-24493" srcset="https://thecodebuzz.com/wp-content/uploads/2022/11/Convert-string-to-numerical-values-in-MongoDB-1024x167.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/11/Convert-string-to-numerical-values-in-MongoDB-300x49.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/11/Convert-string-to-numerical-values-in-MongoDB-768x125.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/11/Convert-string-to-numerical-values-in-MongoDB-1536x251.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2022/11/Convert-string-to-numerical-values-in-MongoDB-785x128.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2022/11/Convert-string-to-numerical-values-in-MongoDB.jpg 1592w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-how-to-convert-data-type-for-all-documents-in-mongo-db"><h3 class="aioseo-faq-block-question">How to convert data type for all documents in Mongo DB</h3><div class="aioseo-faq-block-answer">
<p>You can convert data type for all documents in Mongo DB using the flag Multi as true.</p>



<p></p>
</div></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="75" src="https://www.thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-1024x75.jpg" alt="mongodb change field type from string to number" class="wp-image-24494" srcset="https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-1024x75.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-300x22.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-768x57.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-1536x113.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-785x58.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field.jpg 1766w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-what-is"><h3 class="aioseo-faq-block-question">What is $toInt</h3><div class="aioseo-faq-block-answer">
<p></p>



<p>$toInt is an Aggregation Type Expression Operator that Converts a value to an integer. If the value is null or missing,&nbsp;<a href="https://www.mongodb.com/docs/manual/reference/operator/aggregation/toInt/#mongodb-expression-exp.-toInt"><code>$toInt</code></a>&nbsp;returns null or return errors when the value can not be converted</p>
</div></div>



<p><a href="https://www.mongodb.com/docs/manual/reference/operator/aggregation/toInt/#mongodb-expression-exp.-toInt"></a></p>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-approach-2---remove-the-field-for-all-documents-in-the-mongodb">Example &#8211; Convert a numeric value to a string in MongoDB </h3>



<p></p>



<p><strong>Command</strong>:</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.employee.update({}, [ {$set:{ "EmpID" : {$<strong>toString</strong>: "$EmpID"}}} ], {multi:true})</pre>



<p></p>



<p><strong>Example </strong></p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.employee.update({}, [ {$set:{ "EmpID" : {$<strong>toString</strong>: "$EmpID"}}} ], {multi:true})<br>WriteResult({ "nMatched" : 5, "nUpserted" : 0, "nModified" : 5})</pre>



<p></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-what-is-tostring"><h3 class="aioseo-faq-block-question">What is $toString<br></h3><div class="aioseo-faq-block-answer">
<p>$toString is an aggregation function that Converts a value to a string. If the value is null or missing,&nbsp;<a href="https://www.mongodb.com/docs/manual/reference/operator/aggregation/toInt/#mongodb-expression-exp.-toInt"><code>$</code></a><code>toString</code>&nbsp;returns null or return errors when the value can not be converted</p>
</div></div>



<p> </p>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-approach-3---remove-the-field-for-all-documents-in-the-database-using-updatemany">Example &#8211; Convert a NumberLong to a String</h3>



<p></p>



<p><strong>Command</strong>:</p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.employee.update({}, [ {$set:{ "Ssn" : {$<strong>toString</strong>: "$Ssn"}}} ], {multi:true})</pre>



<p></p>



<p>In the above example, Ssn is a long number data type field that we are converting to string type.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-aggregation-operators-like-convert"><span style="font-size: revert; color: initial;">Using Aggregation Operators like  </span>$convert </h2>



<p></p>



<p>Using this option, one can easily create an aggregation pipeline using $Convert operation which lets you convert field type easily. </p>



<p><br>Example:</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
db.employee.aggregate(
  &#x5B;
    {
      $project:
        { 
          result: 
          {
            $convert: { 
              input: &quot;$EmpID&quot;, 
              to: &quot;string&quot;,
              onError: &quot;An error occurred for the conversion&quot;,
              onNull: &quot;Input was null or empty&quot; 
            }
          }
        }
    }
  ]
).pretty()
</pre></div>


<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-using-Convert-1024x637.jpg" alt="mongodb compass change field type for all documents" class="wp-image-24500" width="790" height="491" srcset="https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-using-Convert-1024x637.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-using-Convert-300x187.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-using-Convert-768x478.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-using-Convert-785x488.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2022/11/MongoDB-Change-The-Type-of-a-field-using-Convert.jpg 1318w" sizes="auto, (max-width: 790px) 100vw, 790px" /></figure>



<p></p>



<p>With pretty print, you can get the expression results on the screen as shown above.</p>



<p></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p>



<p></p><p>The post <a href="https://thecodebuzz.com/mongodb-change-type-of-a-field-convert-string-numeric/">MongoDB Change The Type of a field –  Guidelines</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/mongodb-change-type-of-a-field-convert-string-numeric/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>MongoDB does not Contain a String query with examples</title>
		<link>https://thecodebuzz.com/mongodb-does-not-contain-a-string-query-with-examples/</link>
					<comments>https://thecodebuzz.com/mongodb-does-not-contain-a-string-query-with-examples/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 21 Aug 2022 00:29:00 +0000</pubDate>
				<category><![CDATA[Mongo]]></category>
		<category><![CDATA[mongodb array does not contain]]></category>
		<category><![CDATA[mongodb check if field is string]]></category>
		<category><![CDATA[mongodb match string]]></category>
		<category><![CDATA[mongodb not equal]]></category>
		<category><![CDATA[mongodb not string]]></category>
		<category><![CDATA[mongodb regex not contains]]></category>
		<category><![CDATA[nor in mongodb]]></category>
		<category><![CDATA[not in mongodb aggregate]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=23323</guid>

					<description><![CDATA[<p>MongoDB doesn&#8217;t Contain a String query Today in this article, we will see how to search records in MongoDB does not contain a string. We will learn to search a string and match documents based on case-sensitive and insensitive searches in this informative article. Multiple approaches are covered, including using a like query or regex [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/mongodb-does-not-contain-a-string-query-with-examples/">MongoDB does not Contain a String query with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">MongoDB doesn&#8217;t Contain a String query</h1>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-1024x292.jpg" alt="MongoDB does not Contain a String" class="wp-image-23326" width="757" height="215" srcset="https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-1024x292.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-300x86.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-768x219.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-1536x438.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-785x224.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String.jpg 1633w" sizes="auto, (max-width: 757px) 100vw, 757px" /></figure>



<p>Today in this article, we will see how to search records in MongoDB does not contain a string. </p>



<p></p>



<p>We will learn to search a string and match documents based on case-sensitive and insensitive searches in this informative article.</p>



<p></p>



<p>Multiple approaches are covered, including using a like query or regex query.</p>



<p></p>



<p>We will see multiple approaches to achieve the same like using a like query or regex query etc.</p>



<p></p>



<p>Today in this article, we will cover below aspects,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-mongodb-get-record-that-contains-a-string--approach-1">MongoDB does not Contain a String</a><ul><li><a href="#aioseo-mongodb-does-not-contain-a-string-case-insensitive">MongoDB does not Contain a String &#8211; Case sensitive</a></li><li><a href="#aioseo-command">Command</a></li><li><a href="#aioseo-example">Example</a></li><li><a href="#aioseo-mongodb-does-not-contain-a-string-case-insensitive">MongoDB does not Contain a String &#8211;  Case insensitive</a></li><li><a href="#aioseo-command">Command</a></li><li><a href="#block-95faece7-a550-47d7-982f-1213954e9539">Example</a></li></ul></li></ul></div>



<p></p>



<p></p>



<p>Let&#8217;s take the example below to learn the query.</p>



<p></p>



<p>I have a sample <em><strong>MongoDB </strong></em>document below in one of the collections. </p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
&#x5B;
  {
    &quot;_id&quot;: &quot;5db5a4476997188b2722c820&quot;,
    &quot;Name&quot;: &quot;Design Patterns&quot;,
    &quot;Price&quot;: 54.93,
    &quot;Category&quot;: &quot;Computers&quot;,
    &quot;Author&quot;: &quot;Ralph Johnson&quot;
  },
  {
    &quot;_id&quot;: &quot;5ff50353a29ce9564c2724e2&quot;,
    &quot;Name&quot;: &quot;Design Patterns&quot;,
    &quot;Price&quot;: 54.93,
    &quot;Category&quot;: &quot;Computers&quot;,
    &quot;Author&quot;: &quot;Mike Casper&quot;
  },
  {
    &quot;_id&quot;: &quot;5ff503cda29ce9564c2724e3&quot;,
    &quot;Name&quot;: &quot;Design Patterns&quot;,
    &quot;Price&quot;: 54.93,
    &quot;Category&quot;: &quot;Computers&quot;,
    &quot;Author&quot;: &quot;Julia Robert&quot;
  },
 {
    &quot;_id&quot;: &quot;5f34a2430c3ca98a8c9052d2&quot;,
    &quot;Name&quot;: &quot;Design Patterns&quot;,
    &quot;Price&quot;: 54.93,
    &quot;Category&quot;: &quot;Computers&quot;,
    &quot;Author&quot;: &quot;Mike Johnson&quot;
  }
]
</pre></div>


<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-mongodb-get-record-that-contains-a-string--approach-1">MongoDB does not <em>Contain a String</em></h2>



<p></p>



<p>Let&#8217;s build a MongoDB query using a regex for getting documents that don&#8217;t contain a String.</p>



<p></p>



<p><strong><em>Author </em></strong>names where the name contains a word like <strong><em>&#8220;John&#8221;</em></strong> or &#8220;john&#8221; for the <strong><em>Author</em></strong> field value.</p>



<p></p>



<p>Here we are trying to match <em><strong>&#8220;John&#8221;</strong> or &#8220;john&#8221; could be contained</em> at the <em><strong>start </strong>or <strong>last </strong>or in the </em><strong>middle </strong><em>or <strong>anywhere </strong>else of <strong>Author </strong>names</em>.</p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-mongodb-does-not-contain-a-string-case-insensitive">MongoDB does not <em>Contain a String</em> &#8211; Case sensitive </h3>



<p></p>



<h3 class="wp-block-heading" id="aioseo-command"><strong><em>Command </em></strong></h3>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">{ <span class="has-inline-color has-luminous-vivid-orange-color">Field Name</span> : {'$regex' : '^((?!<span class="has-inline-color has-luminous-vivid-orange-color">Field Value</span>).)*$'}}
</pre>



<p></p>



<h3 class="wp-block-heading" id="aioseo-example"><strong><em>Example </em></strong></h3>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">db.Books.find( { {<span class="has-inline-color has-luminous-vivid-orange-color">Author</span>:{'$regex' : '^((?!<span class="has-inline-color has-luminous-vivid-orange-color">John</span>).)*$'}} )</pre>



<p></p>



<p><strong>Mongo Query Result :</strong></p>



<p></p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="617" src="https://www.thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-query-1-1024x617.jpg" alt="
mongodb not equal,
mongodb check if field is string,
mongodb regex not contains,
mongodb array does not contain,
mongodb not string,
not in mongodb aggregate,
mongodb match string,
nor in mongodb," class="wp-image-23328" srcset="https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-query-1-1024x617.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-query-1-300x181.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-query-1-768x463.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-query-1-785x473.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2022/09/MongoDB-does-not-contain-String-query-1.jpg 1168w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p> </p>



<h3 class="wp-block-heading" id="aioseo-mongodb-does-not-contain-a-string-case-insensitive">MongoDB does not Contain a String &#8211;  Case insensitive</h3>



<p></p>



<h3 class="wp-block-heading" id="aioseo-command"><strong><em> <strong><em>Command </em></strong> </em></strong></h3>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">{Field Name :{'$regex' : '^((?!Field Value).)*$', '$options' : 'i'}}
</pre>



<h3 class="wp-block-heading" id="block-95faece7-a550-47d7-982f-1213954e9539"><strong>Example </strong><br></h3>



<pre class="wp-block-preformatted has-medium-font-size">{Author: {$regex: '^((?!John).)*$',$options: 'i'}}
</pre>



<p></p>



<p><strong><em>References : </em></strong></p>



<p><a href="http://twitter.com/intent/tweet?status=MongoDB%20Naming%20Standards%20and%20Guidelines+https://www.thecodebuzz.com/mongo-db-naming-conventions-standards-guidelines/" target="_blank" rel="noreferrer noopener"><br></a><a href="https://plus.google.com/share?url=https://www.thecodebuzz.com/mongo-db-naming-conventions-standards-guidelines/" target="_blank" rel="noreferrer noopener"></a><a href="https://pinterest.com/pin/create/button/?url=https://www.thecodebuzz.com/mongo-db-naming-conventions-standards-guidelines/&amp;media=&amp;description=MongoDB%20Naming%20Standards%20and%20Guidelines" target="_blank" rel="noreferrer noopener"></a></p>



<ul class="wp-block-list">
<li><a href="https://www.thecodebuzz.com/mongo-db-naming-conventions-standards-guidelines/" target="_blank" rel="noopener"><em>MongoDB Naming Standards and Guidelines</em></a></li>
</ul>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/mongodb-does-not-contain-a-string-query-with-examples/">MongoDB does not Contain a String query with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/mongodb-does-not-contain-a-string-query-with-examples/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>MongoDB &#8211; Mock and Unit Test MongoCollection</title>
		<link>https://thecodebuzz.com/mongodb-mock-unit-test-imongocollection-net-core/</link>
					<comments>https://thecodebuzz.com/mongodb-mock-unit-test-imongocollection-net-core/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 11 Aug 2022 14:44:00 +0000</pubDate>
				<category><![CDATA[Mongo]]></category>
		<category><![CDATA[how to mock mongodb collection]]></category>
		<category><![CDATA[how to mock mongodb repository c#]]></category>
		<category><![CDATA[mock mongodb c# xunit]]></category>
		<category><![CDATA[mock<ifindfluent]]></category>
		<category><![CDATA[mongodb mock python]]></category>
		<category><![CDATA[mongodb unit test]]></category>
		<category><![CDATA[mongodb unit test golang.]]></category>
		<category><![CDATA[unit test mongodb c#]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=23433</guid>

					<description><![CDATA[<p>MongoDB &#8211; Mock and Unit Test MongoCollection Today in this short tutorial, we will see how to Mock and Unit Test MongoCollection and IMongoCollection used in the MongoDB .NET driver library. MongoCollection mocking could be useful considering the complex extension method supported by MongoDB drivers which is not only difficult to mock but also unit [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/mongodb-mock-unit-test-imongocollection-net-core/">MongoDB – Mock and Unit Test MongoCollection</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">MongoDB &#8211; Mock and Unit Test MongoCollection</h1>



<p>Today in this short tutorial, we will see how to  Mock and Unit Test MongoCollection and IMongoCollection used in the MongoDB .NET driver library.</p>



<p></p>



<p>MongoCollection mocking could be useful considering the complex extension method supported by MongoDB drivers which is not only difficult to mock but also unit tested.</p>



<p></p>



<p>Below is a sample code for the Mocking MongoCollection class</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
        var settings = new MongoCollectionSettings();
            var mockCollection = new Mock&lt;IMongoCollection&lt;Book&gt;&gt; { DefaultValue = DefaultValue.Mock };
            mockCollection.SetupGet(s =&gt; s.DocumentSerializer).Returns(settings.SerializerRegistry.GetSerializer&lt;Book&gt;());
            mockCollection.SetupGet(s =&gt; s.Settings).Returns(settings);
            return mockCollection;
</pre></div>


<p></p>



<p>Above the &#8220;<strong>Book</strong>&#8221; class is a model object supporting book schema within the MongoDB database.</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
public class Book
    {
        &#x5B;BsonId]
        &#x5B;BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        public string BookName { get; set; }

        public decimal Price { get; set; }

        public string Category { get; set; }

        public string Author { get; set; }
    }
</pre></div>


<p></p>



<p>Below is a sample example using the above mock scenario,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
       &#x5B;Fact]
        public async void Test_GetBooksAsync_Verify()
        {
            //Arrange
            var mockContext = new Mock&amp;lt;IMongoContext&gt;();
            var mockCollection = CreateMockCollection();
            var collection = mockCollection.Object;

            Book document = new Book();
            document.Author = &quot;asdas&quot;;
            document.BookName = &quot;sadasd&quot;;
            document.Id = ObjectId.GenerateNewId().ToString();
            mockCollection.Object.InsertOne(document);

            BookstoreDatabaseSettings setting = new BookstoreDatabaseSettings();
            setting.BooksCollectionName = &quot;Book&quot;;
            var mockIDBsettings = new Mock&amp;lt;IOptions&amp;lt;BookstoreDatabaseSettings&gt;&gt;();

            mockContext.Setup(x =&gt; x.GetCollection&amp;lt;Book&gt;(&quot;Book&quot;)).Returns(mockCollection.Object);
            mockIDBsettings.Setup(x =&gt; x.Value).Returns(setting);

            //Act

            BookService service = new BookService(mockIDBsettings.Object, mockContext.Object);
            var result = await service.GetBooksAsync();

            //ASSERT
            mockContext.Verify(x =&gt; x.GetCollection&amp;lt;Book&gt;(&quot;Book&quot;), Times.Once);
            mockCollection.Verify(m =&gt; m.FindAsync&amp;lt;Book&gt;(FilterDefinition&amp;lt;Book&gt;.Empty, null, CancellationToken.None), Times.Once);
        }
</pre></div>


<p></p>



<p>Above extension, methods are Asserted for verifying, if they are called in the code execution or not. Additionally, you can add more assertions for the results you get from the method. Please visit this article for more information on how to <a href="https://www.thecodebuzz.com/unit-testing-controller-sync-and-async-methods-asp-net-core-example/" target="_blank" rel="noopener" title="Unit Test and Mock Sync/Async Controller Methods in ASP.NET Core">verify controller methods</a></p>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/mongodb-mock-unit-test-imongocollection-net-core/">MongoDB – Mock and Unit Test MongoCollection</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/mongodb-mock-unit-test-imongocollection-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>MongoDB to Find the Objects between two  dates</title>
		<link>https://thecodebuzz.com/mongodb-to-find-objects-between-two-dates/</link>
					<comments>https://thecodebuzz.com/mongodb-to-find-objects-between-two-dates/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 04 May 2022 20:36:00 +0000</pubDate>
				<category><![CDATA[Mongo]]></category>
		<category><![CDATA[get data between two dates in mongodb]]></category>
		<category><![CDATA[get data between two dates in mongodb in spring boot]]></category>
		<category><![CDATA[how to find data between two dates in mongoose]]></category>
		<category><![CDATA[mongodb between two dates]]></category>
		<category><![CDATA[mongodb compare two date fields]]></category>
		<category><![CDATA[mongodb filter by date without time]]></category>
		<category><![CDATA[mongodb query greater than and less than date]]></category>
		<category><![CDATA[node js mongodb find between dates]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=22792</guid>

					<description><![CDATA[<p>MongoDB &#8211; Find the Objects between two dates Today this article will see how to write a query in MongoDB to find the objects between two dates. We shall see examples with dates using timestamp fields (if available) or using Mongo-defined timestamp available via _Id as objectId. Today in this article, we will cover below [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/mongodb-to-find-objects-between-two-dates/">MongoDB to Find the Objects between two  dates</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">MongoDB &#8211; Find the Objects between two dates</h1>



<figure class="wp-block-image size-large is-resized"><a href="https://www.thecodebuzz.com/mongodb-to-find-objects-between-two-dates" target="_blank" rel="noopener"><img loading="lazy" decoding="async" src="https://www.thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-greater-than-or-lesss-than-Date-C-query-1024x292.jpg" alt="MongoDB to Find the Objects between two dates" class="wp-image-13556" width="537" height="153" srcset="https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-greater-than-or-lesss-than-Date-C-query-1024x292.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-greater-than-or-lesss-than-Date-C-query-300x86.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-greater-than-or-lesss-than-Date-C-query-768x219.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-greater-than-or-lesss-than-Date-C-query-1536x438.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-greater-than-or-lesss-than-Date-C-query-785x224.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-greater-than-or-lesss-than-Date-C-query.jpg 1633w" sizes="auto, (max-width: 537px) 100vw, 537px" /></a></figure>



<p>Today this article will see how to write a query in MongoDB to find the objects between two dates. We shall see examples with dates using timestamp fields (if available) or using Mongo-defined timestamp available via <strong><em>_Id as objectId</em></strong>.</p>



<p>Today in this article, we will cover below aspects,</p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-started">Getting started</a></li><li><a href="#aioseo-using-the-custom-date-field-if-available">Using the Custom Date field (if available)</a></li><li><a href="#aioseo-find-objects-using-cli-or-compass-ui">Find objects using CLI or Compass UI</a><ul><li><a href="#aioseo-find-the-mongodb-documents-when-the-date-is-a-greater-specified-date">Find the MongoDB Documents when the Date is a greater specified date</a></li><li><a href="#aioseo-find-the-mongodb-documents-date-is-less-than-the-specified-date">Find the MongoDB Documents date is less than the specified date</a></li><li><a href="#aioseo-find-the-objects-using-the-_id-field-i-e-objectid">Find the Objects using the _Id field i.e ObjectId</a></li></ul></li></ul></div>



<p></p>



<p>Approaches to get the records between two dates,</p>



<p></p>



<ul class="wp-block-list"><li>Using the dates field if exist</li></ul>



<ul class="wp-block-list"><li>Using MongoDB _Id ObjectId field</li></ul>



<p></p>



<p>We will see greater than or less than date queries using<strong> <em>CLI or  Compass UI</em></strong>.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-getting-started">Getting started</h2>



<p></p>



<h2 class="wp-block-heading" id="aioseo-using-the-custom-date-field-if-available"><strong>Using the Custom Date field (if available)</strong></h2>



<p></p>



<p>Do you follow schema-driven development?</p>



<p></p>



<p>If your schema already has any <em><strong>date or timestamp field</strong></em> then you can use the same to query to get all the records. Here below is a sample schema or document we shall use where I have a custom date field called &#8220;<em><strong>DateAdded</strong></em>&#8220;</p>



<p></p>



<p><strong>Example</strong>:</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; highlight: [4]; title: ; notranslate">
{
  &quot;_id&quot;: &quot;62c5e3f602514a766441e2ef&quot;,
  &quot;UserId&quot;: 999999,
  &quot;DateAdded&quot;: &quot;2021-01-01T05:00:00.000Z&quot;,
  &quot;Books&quot;: &#x5B;
    {
      &quot;book_name&quot;: &quot;book_name1&quot;,
      &quot;price&quot;: 88,
      &quot;category&quot;: &#x5B;
        {
          &quot;key&quot;: &quot;Test1&quot;,
          &quot;value&quot;: &quot;60&quot;
        }
      ]
    },
    {
      &quot;book_name&quot;: &quot;book_name2&quot;,
      &quot;price&quot;: 50,
      &quot;category&quot;: &#x5B;
        {
          &quot;key&quot;: &quot;test3&quot;,
          &quot;value&quot;: &quot;60&quot;
        },
        {
          &quot;key&quot;: &quot;test4&quot;,
          &quot;value&quot;: &quot;100&quot;
        }
      ]
    }
  ]
}
</pre></div>


<p></p>



<h2 class="wp-block-heading" id="aioseo-find-objects-using-cli-or-compass-ui">Find objects using CLI or Compass UI </h2>



<p></p>



<p>Here we will be using the below query to get the documents between two dates in MongoDB Collection.</p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-find-the-mongodb-documents-when-the-date-is-a-greater-specified-date">Find the MongoDB Documents when the Date is a greater specified date</h3>



<p></p>



<p><strong>Command </strong></p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">{ &lt;Field Name&gt;: { $gt:ISODate('Date here') } }

 </pre>



<h3 class="wp-block-heading" id="aioseo-find-the-mongodb-documents-date-is-less-than-the-specified-date">Find the MongoDB Documents date is less than the specified date</h3>



<p></p>



<p> <strong>Command </strong> </p>



<p></p>



<pre id="block-0c76aa9e-4113-436b-874c-263dc8417774" class="wp-block-preformatted has-medium-font-size">{ &lt;Field Name&gt;: { $lt:ISODate('Date here') } }
</pre>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="433" src="https://www.thecodebuzz.com/wp-content/uploads/2022/07/Find-the-Objects-between-two-dates-MongoDB-1024x433.jpg" alt="MongoDB Find the Objects between two dates" class="wp-image-22797" srcset="https://thecodebuzz.com/wp-content/uploads/2022/07/Find-the-Objects-between-two-dates-MongoDB-1024x433.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2022/07/Find-the-Objects-between-two-dates-MongoDB-300x127.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2022/07/Find-the-Objects-between-two-dates-MongoDB-768x325.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2022/07/Find-the-Objects-between-two-dates-MongoDB-1536x650.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2022/07/Find-the-Objects-between-two-dates-MongoDB-785x332.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2022/07/Find-the-Objects-between-two-dates-MongoDB.jpg 1921w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p>For more details on other queries, please refer below article </p>



<p></p>



<ul class="wp-block-list"><li><a href="https://www.thecodebuzz.com/mongodb-date-range-query-greater-than-less-than/" title="MongoDB Date Range query greater than or less than"><strong>Mon</strong></a><a href="https://www.thecodebuzz.com/mongodb-date-range-query-greater-than-less-than/" target="_blank" rel="noreferrer noopener" title="MongoDB Date Range query greater than or less than"><strong><em>goDB Date Range query greater than or less than</em></strong></a></li></ul>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-find-the-objects-using-the-_id-field-i-e-objectid"><strong>Find the Objects using the _Id field i.e ObjectId </strong></h3>



<p></p>



<p>This is another approach typically useful when you don&#8217;t have any timestamp or date field in your schema.</p>



<p></p>



<p>As we know, MongoDB uses the <strong><em>_id </em></strong><em>f</em>ield as <strong><em>ObjectId</em></strong>. This Id has few behavioral characteristics. </p>



<p></p>



<p>It is a <strong><em>4-byte</em></strong> timestamp is a UNIX timestamp. </p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Timestamp represents the <em><strong>ObjectId&#8217;s </strong></em>creation timestamp when a document is inserted into Mongo collection first time, measured in seconds since the Unix epoch. for more details, please visit <a href="https://www.mongodb.com/docs/manual/reference/bson-types/" target="_blank" rel="noreferrer noopener">here</a>.</p></blockquote>



<p></p>



<p><strong>Command</strong></p>



<p></p>



<pre class="wp-block-preformatted has-medium-font-size">{ &lt;field Name&gt;: { $gt: ObjectId.fromDate( new ISODate("Date here"))}}
</pre>



<p>OR</p>



<pre class="wp-block-preformatted has-medium-font-size"> &lt;field Name&gt;: { $lt: ObjectId.fromDate( new Date("Date here"))}} 

</pre>



<p></p>



<p style="font-size:18px">Do you have any <strong>comments or ideas or any better </strong>suggestions to share?</p>



<p class="has-small-font-size"></p>



<p style="font-size:18px">Please sound off your comments below.</p>



<p class="has-medium-font-size"></p>



<p class="has-medium-font-size"><strong>Happy Coding </strong>!!</p>



<p></p>



<hr>



<p class=""></p>



<p class="has-background" style="background-color:#b6d9ac;font-size:18px"><br>Please <strong><em>bookmark </em></strong>this page and <em><strong>share </strong></em>it with your friends.                                                    Please <a href="https://www.thecodebuzz.com/subscription/" target="_blank" rel="noreferrer noopener"><em><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-luminous-vivid-orange-color"><strong>Subscribe</strong> </mark></em></a>to the blog to receive notifications on freshly published (2025) best practices and guidelines for software design and development.</p>




<br>



<hr>



<p class=""></p>



<p></p><p>The post <a href="https://thecodebuzz.com/mongodb-to-find-objects-between-two-dates/">MongoDB to Find the Objects between two  dates</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/mongodb-to-find-objects-between-two-dates/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
