<?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>MongoDB and Mongoose - TheCodeBuzz</title>
	<atom:link href="https://thecodebuzz.com/category/mongodb-and-mongoose/feed/" rel="self" type="application/rss+xml" />
	<link>https://thecodebuzz.com</link>
	<description>Best Practices for Software Development</description>
	<lastBuildDate>Sat, 09 Mar 2024 22:24:28 +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>MongoDB and Mongoose - TheCodeBuzz</title>
	<link>https://thecodebuzz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>C# .NET MongoDB Replace string using $replaceOne</title>
		<link>https://thecodebuzz.com/c-net-mongodb-replace-string-using-replaceone/</link>
					<comments>https://thecodebuzz.com/c-net-mongodb-replace-string-using-replaceone/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 13 Jan 2024 20:57:26 +0000</pubDate>
				<category><![CDATA[MongoDB and Mongoose]]></category>
		<category><![CDATA[C# .NET MongoDB Replace string]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=29406</guid>

					<description><![CDATA[<p>C# .NET MongoDB Replace string using $replaceOne Today this article will learn to write a query using C# .NET MongoDB Replace string using $replaceOne aggregation example. We will replace a string in the Mongo document with the input string using a simple and easy approach i.e using $replaceOne aggregation operator. We will cover below aspects, [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/c-net-mongodb-replace-string-using-replaceone/">C# .NET MongoDB Replace string using $replaceOne</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">C# .NET MongoDB Replace string using $replaceOne</h1>



<figure class="wp-block-image size-large is-resized"><img fetchpriority="high" decoding="async" width="1024" height="310" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-1024x310.jpg" alt="#image_title #separator_sa #post_seo_title" class="wp-image-29401" style="width:739px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-1024x310.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-300x91.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-768x232.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-1536x464.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-785x237.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell.JPG 1548w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today this article will learn to write a query using C# .NET MongoDB Replace string using $replaceOne aggregation example.</p>



<p></p>



<p>We will replace a string in the Mongo document with the input string using a simple and easy approach i.e using  <strong><em><code>$replaceOne</code> </em></strong>aggregation operator.</p>



<p></p>



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



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-started">Getting started</a></li><li><a href="#aioseo-step-i--establish-the-connection-with-mongodb-driver">Step I &#x2013; Establish the connection with the MongoDB driver</a></li><li><a href="#aioseo-step-ii--get-all-the-records-from-the-given-collection">Step II &#x2013; Get the collection object for the given Mongo Database</a></li><li><a href="#aioseo-mongo-field-length-query-using-cli-or-compass-ui">C#.NET &#8211; Replace Substring in MongoDB using $replaceOne Aggregator</a><ul><li><a href="#aioseo-what-is-replaceone">What is $replaceOne</a></li></ul></li><li><a href="#aioseo-query-pattern-replace-using-replaceone">Query Pattern Replace using $replaceOne</a><ul><li><a href="#aioseo-example-using-replaceone">Example using $replaceOne</a></li></ul></li><li><a href="#aioseo-create-update-pipeline">Create Update Pipeline</a></li></ul></div>



<p>&nbsp;</p>



<p></p>



<p>We will update the records using the Mongo shell query.</p>



<p></p>



<p></p>



<p>We already looked at a simple way of adding or updating a new field to the document in our previous&nbsp;<strong><a href="https://www.thecodebuzz.com/mongodb-add-new-field-every-document-in-mongodb-collection/" target="_blank" rel="noreferrer noopener">MongoDB sample series</a>.</strong></p>



<p></p>



<p></p>



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



<p></p>



<p>Please add the&nbsp;<strong><em>MongoDB driver&nbsp;</em></strong>NuGet package using the Nuget Package manager.</p>



<p></p>



<pre class="wp-block-preformatted">PM&gt; Install-Package MongoDB.Driver -Version &lt;version&gt;</pre>



<p><strong><em>Note&nbsp;</em></strong>– Please use the<strong><em>&nbsp;latest version</em></strong>&nbsp;available.</p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-step-i--establish-the-connection-with-mongodb-driver">Step I – Establish the connection with the MongoDB driver</h2>



<p></p>



<pre class="wp-block-preformatted">var _mongoClient = new MongoClient("mongodb://your connection string"); 

var db = _mongoClient.GetDatabase("TheCodeBuzz");
</pre>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-step-ii--get-all-the-records-from-the-given-collection">Step II – Get the collection object for the given Mongo Database</h2>



<p></p>



<pre class="wp-block-preformatted">var collection = db.GetCollection("Orders");
</pre>



<p></p>



<p>Here below is a sample schema or document we shall use,</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" width="1024" height="508" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1024x508.jpg" alt="C# .NET MongoDB Replace string" class="wp-image-29398" style="width:813px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1024x508.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-300x149.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-768x381.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1536x762.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-785x390.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document.jpg 1926w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<pre class="wp-block-code"><code>
</code></pre>



<h2 class="wp-block-heading" id="aioseo-mongo-field-length-query-using-cli-or-compass-ui">C#.NET &#8211; Replace Substring in MongoDB using $replaceOne Aggregator </h2>



<p></p>



<p>We are going to use a newly introduced aggregate operator to replace easily a string with matching criteria with part of the string.</p>



<p></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-what-is-replaceone"><h3 class="aioseo-faq-block-question">What is <code>$replaceOne</code></h3><div class="aioseo-faq-block-answer">
<p><a href="https://www.mongodb.com/docs/upcoming/reference/operator/aggregation/replaceOne/#mongodb-expression-exp.-replaceOne" target="_blank" rel="noopener" title=""><code>$replaceOne</code></a> is aggregation operator which helps replace the first instance of a search string in an input string with a replacement string.</p>



<p></p>



<p>This operator usage&nbsp;is <em>case-sensitive</em>.</p>



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



<h2 class="wp-block-heading" id="aioseo-query-pattern-replace-using-replaceone">Query Pattern Replace using $replaceOne</h2>



<p></p>



<pre class="wp-block-code has-medium-font-size"><code>{ 
 $replaceOne: { 
    input: &lt;expression&gt;, 
    find: &lt;expression&gt;, 
    replacement: &lt;expression&gt;}
}
</code></pre>



<p>In the above query,</p>



<p></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>input</td><td>Input string with search criteria.</td></tr><tr><td>find</td><td>Find the document with matching input string criteria.</td></tr><tr><td>replacement</td><td>The string to use to replace the first matched instance from input</td></tr></tbody></table></figure>



<p></p>



<p>You can replace the existing Mongo field using any other fields from the document using the above approach + using the approach discussed <a href="https://www.thecodebuzz.com/mongodb-add-padding-logic-with-prefix-or-suffix-examples/" target="_blank" rel="noopener" title="MongoDB – Add Padding logic with prefix or suffix examples">here</a>.</p>



<p></p>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-example-using-replaceone">Example using $replaceOne</h3>



<p></p>



<p>In the below example, we will replace &#8220;total-order&#8221; with &#8220;order&#8221; in the mongo field.</p>



<p>Add below using the required for MognoDB query execution,</p>



<p></p>



<pre class="wp-block-code"><code>using MongoDB.Bson;
using MongoDB.Driver;
using System.Text.RegularExpressions;

</code></pre>



<p></p>



<p><strong>Mongo Filter Query </strong></p>



<p></p>



<p>Below query filter all the records with the &#8220;Link&#8221; field value matching with the &#8220;total-order&#8221; value.</p>



<p></p>



<pre class="wp-block-preformatted">var filter = new BsonDocument("Link", new BsonDocument("$regex", new Regex("total-order")));</pre>



<p></p>



<p><strong>MongoDB C# $replaceOne</strong> <strong> Query </strong></p>



<p></p>



<p>Below represent a C# representation of the aggregation query,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
var query = new BsonDocument(&quot;Link&quot;, new BsonDocument(&quot;$regex&quot;, new Regex(&quot;total-order&quot;))),new BsonArray
{
    new BsonDocument(&quot;$set&quot;, 
    new BsonDocument(&quot;Link&quot;, 
    new BsonDocument(&quot;$replaceOne&quot;, 
    new BsonDocument
                {
                    { &quot;input&quot;, &quot;$Link&quot; }, 
                    { &quot;find&quot;, &quot;total-order&quot; }, 
                    { &quot;replacement&quot;, &quot;order&quot; }
                })))
}
</pre></div>


<p></p>



<p>Complete the sample as below,</p>



<p></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: csharp; title: ; notranslate">
_mongoClient = new MongoClient(connectionString);

 
var db = _mongoClient.GetDatabase(&quot;TheCodeBuzz&quot;);

var collection = db.GetCollection&lt;BsonDocument&gt;(&quot;Books&quot;);

 var filter = new BsonDocument(&quot;Link&quot;, new BsonDocument(&quot;$regex&quot;, new Regex(&quot;total-order&quot;)));

            BsonDocument doc = new BsonDocument();

            var stageBson=  new BsonDocument
            {
                new BsonDocument(&quot;$set&quot;,
                new BsonDocument(&quot;Link&quot;,
                new BsonDocument(&quot;$replaceOne&quot;,
                new BsonDocument
                            {
                                { &quot;input&quot;, &quot;$Link&quot; },
                                { &quot;find&quot;, &quot;total-order&quot; },
                                { &quot;replacement&quot;, &quot;order&quot; }
                            })))
            };
            doc.AddRange(stageBson);


          
</pre></div>


<h2 class="wp-block-heading" id="aioseo-create-update-pipeline">Create Update Pipeline</h2>



<p></p>



<p>Below is how you can create an update pipeline instance as below.</p>



<p></p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="151" src="https://www.thecodebuzz.com/wp-content/uploads/2024/01/image-1-2-1024x151.jpg" alt="Create Pipeline for $replaceOne" class="wp-image-29933" srcset="https://thecodebuzz.com/wp-content/uploads/2024/01/image-1-2-1024x151.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2024/01/image-1-2-300x44.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2024/01/image-1-2-768x114.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2024/01/image-1-2-785x116.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2024/01/image-1-2.jpg 1487w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">#image_title #separator_sa #post_seo_title</figcaption></figure>



<p></p>



<p>Below is the document post replacing the value of fields.</p>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="600" height="299" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-query.jpg" alt="C# $replaceOne example" class="wp-image-29399" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-query.jpg 600w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-query-300x150.jpg 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /></figure>



<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/c-net-mongodb-replace-string-using-replaceone/">C# .NET MongoDB Replace string using $replaceOne</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/c-net-mongodb-replace-string-using-replaceone/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>PyMongo &#8211; Insert datetime as ISODate in Python</title>
		<link>https://thecodebuzz.com/pymongo-insert-datetime-as-isodate-in-python/</link>
					<comments>https://thecodebuzz.com/pymongo-insert-datetime-as-isodate-in-python/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 17 Dec 2023 17:29:50 +0000</pubDate>
				<category><![CDATA[MongoDB and Mongoose]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python-How to]]></category>
		<category><![CDATA[PyMongo - Insert datetime as ISODate in Python]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=29348</guid>

					<description><![CDATA[<p>PyMongo &#8211; Insert datetime into Mongodb as ISODate Today in this article, we will see how to perform PyMongo &#8211; Insert datetime as ISODate in Python. We will use Mongo Driver called pymongo to insert the date in the collection in the ISO format. Getting started Here below is a sample schema or document we [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/pymongo-insert-datetime-as-isodate-in-python/">PyMongo – Insert datetime as ISODate in Python</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">PyMongo &#8211; Insert datetime into Mongodb as ISODate </h1>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="315" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-1024x315.jpg" alt="#image_title #separator_sa #post_seo_title" class="wp-image-29350" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-1024x315.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-300x92.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-768x236.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-785x241.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python.jpg 1340w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today in this article, we will see how to perform PyMongo &#8211; Insert datetime as ISODate in Python.</p>



<p></p>



<p>We will use Mongo Driver called <em>pymongo </em>to insert the date in the collection in the ISO format.</p>



<p></p>



<p></p>



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



<p></p>



<p>Here below is a sample schema or document we shall use for the date range query,</p>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="636" height="535" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-update_many-in-PyMongo.jpg" alt="" class="wp-image-29357" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-update_many-in-PyMongo.jpg 636w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-update_many-in-PyMongo-300x252.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-update_many-in-PyMongo-618x520.jpg 618w" sizes="auto, (max-width: 636px) 100vw, 636px" /></figure>



<h2 class="wp-block-heading" id="aioseo-install-pymongo-pcakge">Install PyMongo package</h2>



<p></p>



<p>Please install the PyMongo driver package to get support for the MongoClient connection class and properties.</p>



<p></p>



<p>For more details visit-<a href="https://api.mongodb.com/python/current" target="_blank" rel="noreferrer noopener"> <em>https://api.mongodb.com/python/current</em></a></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-add-pymongo-import-statements">Add PyMongo Import statements</h2>



<p></p>



<p>Please add below using namespaces,</p>



<p></p>



<pre class="wp-block-preformatted">from pymongo import MongoClient

from datetime import datetime</pre>



<p></p>



<p>If you need support for date <strong>time zone s</strong>upport in <strong>UTC, ETC, </strong>etc, please add below other import statements.</p>



<p></p>



<pre class="wp-block-preformatted">from datetime import datetime, tzinfo, timezone</pre>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-mongo-date-query-using-cli-or-compass-ui">Define MongoDB Connection</h2>



<p></p>



<pre class="wp-block-code"><code>client = MongoClient('mongodb://localhost:27017/')
db = client&#91;'your_database']
collection = db&#91;'your_collection']


</code></pre>



<h2 class="wp-block-heading" id="aioseo-date-greater-than-query">Python – Insert Date Time in ISO format</h2>



<p></p>



<h3 class="wp-block-heading" id="aioseo-define-the-date-for-the-query">Define the date for the query</h3>



<p></p>



<pre class="wp-block-code"><code>
date = datetime(2023, 1, 1)
</code></pre>



<p></p>



<p>OR</p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-date-time-using-time-zone">Date time using time zone</h3>



<p></p>



<pre class="wp-block-code"><code>date = datetime(2023, 1, 1, tzinfo=timezone.utc)
</code></pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong><em>Note</em></strong>:  When used with <strong>datetime</strong>, <em><strong>MongoDB by default uses ISO format to insert</strong></em> any date in the mongo collection.</p>
</blockquote>



<p></p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-define-the-filter">Define the filter</h3>



<p></p>



<pre class="wp-block-code"><code>filter =  { //define any filter as needed }
</code></pre>



<p></p>



<p></p>



<h3 class="wp-block-heading">Define the update operation</h3>



<p></p>



<p>Please define the update operation (<code>update_operation</code>) to fit your data structure and update requirements as needed. </p>



<p></p>



<p>Below we are setting the &#8220;Date&#8221; the date field with ISO date in all the documents in the collection.</p>



<p></p>



<p></p>



<pre class="wp-block-code"><code># Define the update operation

update_operation = {
    '$set': {
        'ModifiedDate': date
    }
}
</code></pre>



<p></p>



<h2 class="wp-block-heading">Perform update_many to insert the ISO date</h2>



<p></p>



<p>Let&#8217;s perform the update_many operations as below. <code>update_many</code> in PyMongo permits you to update multiple documents that match a specified filter.</p>



<p></p>



<p>We simplification purposes, we will insert the ISO date in every document using <code>update_many</code>.</p>



<p></p>



<pre class="wp-block-code"><code>result = collection.update_many({},update_operation)

</code></pre>



<p>Above I have defined an empty filter.</p>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1005" height="576" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-est.jpg" alt="PyMongo - Insert datetime as ISODate" class="wp-image-29352" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-est.jpg 1005w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-est-300x172.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-est-768x440.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/pymongo-iso-date-mongo-python-est-785x450.jpg 785w" sizes="auto, (max-width: 1005px) 100vw, 1005px" /><figcaption class="wp-element-caption">#image_title #separator_sa #post_seo_title</figcaption></figure>



<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>The post <a href="https://thecodebuzz.com/pymongo-insert-datetime-as-isodate-in-python/">PyMongo – Insert datetime as ISODate in Python</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/pymongo-insert-datetime-as-isodate-in-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Replace Substring in MongoDB document</title>
		<link>https://thecodebuzz.com/replace-substring-in-mongodb-document/</link>
					<comments>https://thecodebuzz.com/replace-substring-in-mongodb-document/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 16 Dec 2023 21:16:29 +0000</pubDate>
				<category><![CDATA[MongoDB and Mongoose]]></category>
		<category><![CDATA[MongoDB replace string]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=29393</guid>

					<description><![CDATA[<p>Replace Substring in MongoDB document Today this article will learn to write a query to replace substring in MongoDB document with an example. We will replace a string in the Mongo document with the input string using a simple and easy approach i.e using $replaceOne aggregation operator. We will cover below aspects, &#160; We will [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/replace-substring-in-mongodb-document/">Replace Substring in MongoDB document</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Replace Substring in MongoDB document</h1>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="310" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-1024x310.jpg" alt="#image_title #separator_sa #post_seo_title" class="wp-image-29401" style="width:739px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-1024x310.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-300x91.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-768x232.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-1536x464.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-785x237.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell.JPG 1548w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today this article will learn to write a query to replace substring in MongoDB document with an example.</p>



<p></p>



<p>We will replace a string in the Mongo document with the input string using a simple and easy approach i.e using  <strong><em><code>$replaceOne</code> </em></strong>aggregation operator.</p>



<p></p>



<p>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-mongo-field-length-query-using-cli-or-compass-ui">Replace Substring in MongoDB using replaceOne Aggregator</a><ul><li><a href="#aioseo-what-is-replaceone">What is $replaceOne</a></li></ul></li><li><a href="#aioseo-query-pattern-replace-using-replaceone">Query Pattern Replace using $replaceOne</a></li><li><a href="#aioseo-example-using-replaceone">Example using $replaceOne</a></li></ul></div>



<p>&nbsp;</p>



<p></p>



<p>We will update the records using the Mongo shell query.</p>



<p></p>



<p></p>



<p></p>



<p>We already looked at a simple way of adding or updating a new field to the document in our previous&nbsp;<strong><a href="https://www.thecodebuzz.com/mongodb-add-new-field-every-document-in-mongodb-collection/" target="_blank" rel="noreferrer noopener">MongoDB sample series</a>.</strong></p>



<p></p>



<p></p>



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



<p></p>



<p>Here below is a sample schema or document we shall use,</p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="508" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1024x508.jpg" alt="" class="wp-image-29398" style="width:813px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1024x508.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-300x149.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-768x381.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1536x762.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-785x390.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document.jpg 1926w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<pre class="wp-block-code"><code>
</code></pre>



<h2 class="wp-block-heading" id="aioseo-mongo-field-length-query-using-cli-or-compass-ui">Replace Substring in MongoDB using replaceOne Aggregator </h2>



<p></p>



<p>We are going to use a newly introduced aggregate operator to replace easily a string with matching criteria with part of the string.</p>



<p></p>



<div data-schema-only="false" class="wp-block-aioseo-faq" id="aioseo-what-is-replaceone"><h3 class="aioseo-faq-block-question">What is <code>$replaceOne</code></h3><div class="aioseo-faq-block-answer">
<p><a href="https://www.mongodb.com/docs/upcoming/reference/operator/aggregation/replaceOne/#mongodb-expression-exp.-replaceOne" target="_blank" rel="noopener" title=""><code>$replaceOne</code></a> is aggregation operator which helps replace the first instance of a search string in an input string with a replacement string.</p>



<p></p>



<p>This operator usage&nbsp;is <em>case-sensitive</em>.</p>



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



<h2 class="wp-block-heading" id="aioseo-query-pattern-replace-using-replaceone">Query Pattern Replace using $replaceOne</h2>



<p></p>



<pre class="wp-block-code has-medium-font-size"><code>{ 
$replaceOne: { 
    input: &lt;expression&gt;, 
    find: &lt;expression&gt;, 
    replacement: &lt;expression&gt;}
}
</code></pre>



<p>In the above query,</p>



<p></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>input</td><td>Input string with search criteria.</td></tr><tr><td>find</td><td>Find the document with matching input string criteria.</td></tr><tr><td>replacement</td><td>The string to use to replace the first matched instance from input</td></tr></tbody></table></figure>



<p></p>



<p>You can replace the existing Mongo field using any other fields from the document using the above approach + using the approach discussed <a href="https://www.thecodebuzz.com/mongodb-add-padding-logic-with-prefix-or-suffix-examples/" target="_blank" rel="noopener" title="MongoDB – Add Padding logic with prefix or suffix examples">here</a>.</p>



<p></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-example-using-replaceone">Example using $replaceOne</h2>



<p></p>



<p>In the below example, we will replace &#8220;total-order&#8221; with &#8220;order&#8221; in the mongo field.</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="508" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-1024x508.jpg" alt="" class="wp-image-29403" style="width:840px;height:auto" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-1024x508.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-300x149.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-768x381.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-1536x762.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1-785x390.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-1.jpg 1926w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



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



<pre class="wp-block-code"><code>db.Orders.updateMany(
{ 
  Link: { 
    $regex: /total-order/ 
  } 
}, 
&#91;{ 
  $set: { 
    Link: { 
      $replaceOne: { 
        input: "$Link", 
        find: "total-order", 
        replacement: "order" 
      } 
    } 
  } 
}])</code></pre>



<p></p>



<p>Below is the schema post-update,</p>



<p></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="600" height="299" src="https://www.thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-query.jpg" alt="Replace Substring in MongoDB document" class="wp-image-29399" srcset="https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-query.jpg 600w, https://thecodebuzz.com/wp-content/uploads/2023/12/Replace-Substring-in-MongoDB-document-shell-query-300x150.jpg 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /></figure>



<p></p>



<p>That&#8217;s all! Happy coding!</p>



<p></p>



<p>Does this help you fix your issue? </p>



<p></p>



<p>Do you have any better solutions or suggestions? Please sound off your comments below.</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/replace-substring-in-mongodb-document/">Replace Substring in MongoDB document</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/replace-substring-in-mongodb-document/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Node.js &#8211; MongoDB Date Time query with examples</title>
		<link>https://thecodebuzz.com/node-js-mongodb-date-time-query-node-mongodb-native/</link>
					<comments>https://thecodebuzz.com/node-js-mongodb-date-time-query-node-mongodb-native/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 19 Nov 2023 00:24:16 +0000</pubDate>
				<category><![CDATA[MongoDB and Mongoose]]></category>
		<category><![CDATA[Node.js]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=28930</guid>

					<description><![CDATA[<p>Node &#8211; MongoDB Date Time query with examples Today, in this article will cover Node.js &#8211; MongoDB Date Time query with examples. We will see how to get records using a date filter like &#8216;greater than&#8217; OR &#8216;less than&#8217; or get the records between 2 dates. We will use the MongoDB Node.js Driver package to [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/node-js-mongodb-date-time-query-node-mongodb-native/">Node.js – MongoDB Date Time query with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Node &#8211; MongoDB Date Time query with examples</h1>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="315" src="https://www.thecodebuzz.com/wp-content/uploads/2023/11/node-js-MongoDB-Date-Time-query-with-examples-1024x315.jpg" alt="Node.js - MongoDB Date Time query with examples-mongoose" class="wp-image-28935" srcset="https://thecodebuzz.com/wp-content/uploads/2023/11/node-js-MongoDB-Date-Time-query-with-examples-1024x315.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/11/node-js-MongoDB-Date-Time-query-with-examples-300x92.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/11/node-js-MongoDB-Date-Time-query-with-examples-768x236.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/11/node-js-MongoDB-Date-Time-query-with-examples-785x241.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/11/node-js-MongoDB-Date-Time-query-with-examples.jpg 1340w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today, in this article will cover Node.js &#8211; MongoDB Date Time query with examples. </p>



<p></p>



<p>We will see how to get records using a date filter like &#8216;greater than&#8217; OR &#8216;less than&#8217; or get the records between 2 dates.</p>



<p></p>



<p>We will use the <em><em>MongoDB Node.js Driver</em></em> <em>package</em> to install the Mongo driver and query MongoDB.</p>



<p>For more details &#8211; <em>https://mongodb.github.io/node-mongodb-native</em></p>



<p></p>



<p></p>



<p>We will cover the below aspects in today&#8217;s article,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-started">Getting started</a></li><li><a href="#aioseo-install-pymongo-pcakge">Install Node.js MongoDB driver</a></li><li><a href="#aioseo-add-pymongo-import-statements">Add MongoDB Import statements</a></li><li><a href="#aioseo-mongo-date-query-using-cli-or-compass-ui">Define MongoDB Connection</a></li><li><a href="#aioseo-date-greater-than-query">Node.js- Mongo Date greater than query (&#x27;gt&#x27;)</a><ul><li><a href="#aioseo-define-the-date">Define the date</a></li><li><a href="#aioseo-define-the-filter">Define the filter</a></li><li><a href="#aioseo-get-the-results">Get the results</a></li><li><a href="#aioseo-below-is-the-complete-code">Complete sample code,</a></li><li><a href="#aioseo-mongo-atlas-ui">Mongo Atlas UI</a></li></ul></li><li><a href="#aioseo-node-js-mongo-date-less-than-query-lt">Node js- Mongo Date less than query (&#x27;lt&#x27;)</a></li><li><a href="#aioseo-node-js-mongo-date-less-than-and-greater-than-date-query">Node js- Mongo Date less than and greater than date query</a></li></ul></div>



<p></p>



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



<p></p>



<p>Here below is a sample schema or document we shall use for the date range query,</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="700" height="878" src="https://www.thecodebuzz.com/wp-content/uploads/2020/09/Add-the-new-field-to-document-in-a-MongoDB-Collection-using-_Id.jpg" alt="Node js mongodb date query" class="wp-image-12234" srcset="https://thecodebuzz.com/wp-content/uploads/2020/09/Add-the-new-field-to-document-in-a-MongoDB-Collection-using-_Id.jpg 700w, https://thecodebuzz.com/wp-content/uploads/2020/09/Add-the-new-field-to-document-in-a-MongoDB-Collection-using-_Id-239x300.jpg 239w, https://thecodebuzz.com/wp-content/uploads/2020/09/Add-the-new-field-to-document-in-a-MongoDB-Collection-using-_Id-415x520.jpg 415w" sizes="auto, (max-width: 700px) 100vw, 700px" /></figure>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-install-pymongo-pcakge">Install Node.js MongoDB driver</h2>



<p></p>



<p>Please install the Node.js MongoDB driver package to get support for the MongoClient connection class and properties. </p>



<p></p>



<p>For more details visit- <a href="https://mongodb.github.io/node-mongodb-native" target="_blank" rel="noopener" title=""> <em>https://mongodb.github.io/node-mongodb-native</em></a></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-add-pymongo-import-statements">Add MongoDB Import statements </h2>



<p></p>



<p>Please add below using namespaces </p>



<p></p>



<pre class="wp-block-preformatted">import { MongoClient } from 'mongodb';</pre>



<p></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-mongo-date-query-using-cli-or-compass-ui">Define MongoDB Connection</h2>



<p></p>



<p>Using MongoClient class define the MongoDB Connection</p>



<p></p>



<pre class="wp-block-code"><code>const client = await MongoClient.connect(
  'mongodb://your server:27017/',
  { useNewUrlParser: true, useUnifiedTopology: true }
);</code></pre>



<p></p>



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



<p></p>



<h2 class="wp-block-heading" id="aioseo-date-greater-than-query">Node.js- Mongo Date greater than query (&#8216;gt&#8217;)</h2>



<p></p>



<h4 class="wp-block-heading" id="aioseo-define-the-date">Define the date </h4>



<p></p>



<pre class="wp-block-code"><code>const queryDate = new Date('2023-11-01');
</code></pre>



<p></p>



<h4 class="wp-block-heading" id="aioseo-define-the-filter">Define the filter </h4>



<p></p>



<p>Lets define the date filter as below,</p>



<p></p>



<pre class="wp-block-code"><code>const filter = {
  'DateAdded': {
    '$gt': queryDate

  }
};


</code></pre>



<h4 class="wp-block-heading" id="aioseo-get-the-results">Get the results </h4>



<p></p>



<pre class="wp-block-code"><code>const coll = client.db('TheCodeBuzz').collection('Books');

const cursor = coll.find(filter);

const result = await cursor.toArray();

await client.close();</code></pre>



<p></p>



<p></p>



<h4 class="wp-block-heading" id="aioseo-below-is-the-complete-code">Complete sample code,</h4>



<p></p>



<pre class="wp-block-code"><code>import { MongoClient } from 'mongodb';

# Define Node Mongo Connection

const client = await MongoClient.connect(
  'mongodb://your server:27017/',
  { useNewUrlParser: true, useUnifiedTopology: true }
);

# define date for the query 

const queryDate = new Date('2023-11-01');

# define filter for the query 

const filter = {
  'DateAdded': {
    '$gt': queryDate

  }
};


const coll = client.db('TheCodeBuzz').collection('Books');
const cursor = coll.find(filter);
const result = await cursor.toArray();
await client.close();


</code></pre>



<p></p>



<h4 class="wp-block-heading" id="aioseo-mongo-atlas-ui"><strong>Mongo Atlas UI</strong></h4>



<p></p>



<p>The above query produces the same result as indicated below using ATLAS UI,</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="433" src="https://www.thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-1024x433.jpg" alt="node js datetime mongodb format, node.js isodate, node  insert datetime now, node mongodb date time query, " class="wp-image-13546" srcset="https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-1024x433.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-300x127.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-768x325.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-1536x650.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-785x332.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass.jpg 1921w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<h2 class="wp-block-heading" id="aioseo-node-js-mongo-date-less-than-query-lt">Node js- Mongo Date less than query (&#8216;lt&#8217;)</h2>



<p></p>



<p>Let&#8217;s define Node.js Mongo Datetime less than query (&#8216;lt&#8217;)</p>



<p></p>



<pre class="wp-block-code"><code># define date for the query 


const queryDate = new Date('2023-11-01');

# define filter for the query 

const filter = {
  'DateAdded': {
    '$lt': queryDate

  }
};</code></pre>



<p></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-node-js-mongo-date-less-than-and-greater-than-date-query">Node js- Mongo Date less than and greater than date query </h2>



<p></p>



<p></p>



<pre class="wp-block-code"><code># define date for the query 

const queryStartDate = new Date('2023-11-01');
const queryEndDate = new Date('2024-01-01');


# define filter for the query 

filter =  {
         'DateAdded': {
                '$gte': queryStartDate,
                '$lt': queryEndDate

         }
  }</code></pre>



<p>For more details on queries where no date field in the schema is available , please visit this article,</p>



<ul class="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>That&#8217;s all! Happy coding!</p>



<p></p>



<p>Does this help you fix your issue? </p>



<p></p>



<p>Do you have any better solutions or suggestions? Please sound off your comments below.</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/node-js-mongodb-date-time-query-node-mongodb-native/">Node.js – MongoDB Date Time query with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/node-js-mongodb-date-time-query-node-mongodb-native/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python &#8211; MongoDB Date Time query with examples</title>
		<link>https://thecodebuzz.com/python-mongodb-date-time-query-pymongo/</link>
					<comments>https://thecodebuzz.com/python-mongodb-date-time-query-pymongo/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 18 Nov 2023 18:58:22 +0000</pubDate>
				<category><![CDATA[MongoDB and Mongoose]]></category>
		<category><![CDATA[Python-How to]]></category>
		<guid isPermaLink="false">https://www.thecodebuzz.com/?p=28916</guid>

					<description><![CDATA[<p>Python &#8211; MongoDB Date Time query with examples Today, in this article will see how to write a MongoDB Date Time query to get records based on timestamp or date range using Python language. We will use the PyMongo package to install the driver and query MongoDB. We will cover the below aspects in today&#8217;s [&#8230;]</p>
<p>The post <a href="https://thecodebuzz.com/python-mongodb-date-time-query-pymongo/">Python – MongoDB Date Time query with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></description>
										<content:encoded><![CDATA[<h1 class="wp-block-heading">Python &#8211; MongoDB Date Time query with examples</h1>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="315" src="https://www.thecodebuzz.com/wp-content/uploads/2023/11/Python-MongoDB-Date-Time-query-with-examples-1024x315.jpg" alt="" class="wp-image-28925" srcset="https://thecodebuzz.com/wp-content/uploads/2023/11/Python-MongoDB-Date-Time-query-with-examples-1024x315.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2023/11/Python-MongoDB-Date-Time-query-with-examples-300x92.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2023/11/Python-MongoDB-Date-Time-query-with-examples-768x236.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2023/11/Python-MongoDB-Date-Time-query-with-examples-785x241.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2023/11/Python-MongoDB-Date-Time-query-with-examples.jpg 1340w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Today, in this article will see how to write a MongoDB Date Time query to get records based on <strong>timestamp </strong>or <strong>date </strong>range using Python language.</p>



<p></p>



<p>We will use the <em>PyMongo package</em> to install the driver and query MongoDB.</p>



<p></p>



<p>We will cover the below aspects in today&#8217;s article,</p>



<p></p>



<div class="wp-block-aioseo-table-of-contents"><ul><li><a href="#aioseo-getting-started">Getting started</a></li><li><a href="#aioseo-install-pymongo-pcakge">Install PyMongo package</a></li><li><a href="#aioseo-add-pymongo-import-statements">Add PyMongo Import statements</a></li><li><a href="#aioseo-mongo-date-query-using-cli-or-compass-ui">Define MongoDB Connection</a><ul><li><a href="#aioseo-date-greater-than-query">Python &#8211; Mongo Date greater than query (&#x27;gt&#x27;)</a></li><li><a href="#aioseo-define-the-date-for-the-query">Define the date for the query</a></li><li><a href="#aioseo-date-time-using-time-zone">Date time using time zone</a></li><li><a href="#aioseo-define-the-filter">Define the filter</a></li><li><a href="#aioseo-get-the-results">Get the results</a><ul><li><a href="#aioseo-mongo-atlas-ui">Mongo Atlas UI</a></li></ul></li></ul></li></ul></div>



<p></p>



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



<p></p>



<p>Here below is a sample schema or document we shall use for the date range query,</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="700" height="878" src="https://www.thecodebuzz.com/wp-content/uploads/2020/09/Add-the-new-field-to-document-in-a-MongoDB-Collection-using-_Id.jpg" alt="Python mongodb date query" class="wp-image-12234" srcset="https://thecodebuzz.com/wp-content/uploads/2020/09/Add-the-new-field-to-document-in-a-MongoDB-Collection-using-_Id.jpg 700w, https://thecodebuzz.com/wp-content/uploads/2020/09/Add-the-new-field-to-document-in-a-MongoDB-Collection-using-_Id-239x300.jpg 239w, https://thecodebuzz.com/wp-content/uploads/2020/09/Add-the-new-field-to-document-in-a-MongoDB-Collection-using-_Id-415x520.jpg 415w" sizes="auto, (max-width: 700px) 100vw, 700px" /></figure>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-install-pymongo-pcakge">Install PyMongo package </h2>



<p></p>



<p>Please install the PyMongo driver package to get support for the MongoClient connection class and properties. </p>



<p></p>



<p>For more details visit-<a href="https://api.mongodb.com/python/current" target="_blank" rel="noopener" title=""> <em>https://api.mongodb.com/python/current</em></a></p>



<p></p>



<p></p>



<h2 class="wp-block-heading" id="aioseo-add-pymongo-import-statements">Add PyMongo Import statements </h2>



<p></p>



<p>Please add below using namespaces </p>



<p></p>



<pre class="wp-block-preformatted">from pymongo import MongoClient

from datetime import datetime</pre>



<p></p>



<p></p>



<p>If you need support for date <strong>time zone s</strong>upport like <strong>UTC </strong>or <strong>ETC </strong>etc, please add below other import statements,</p>



<p></p>



<pre class="wp-block-preformatted">from datetime import datetime, tzinfo, timezone</pre>



<p></p>



<h2 class="wp-block-heading" id="aioseo-mongo-date-query-using-cli-or-compass-ui">Define MongoDB Connection</h2>



<p></p>



<p></p>



<pre class="wp-block-code"><code>client = MongoClient('mongodb://localhost:27017/')
db = client&#91;'your_database']
collection = db&#91;'your_collection']</code></pre>



<p></p>



<p>Here we will be using the below query to get the documents between <a href="https://www.thecodebuzz.com/mongodb-to-find-objects-between-two-dates/" target="_blank" rel="noopener" title="">two dates</a> in MongoDB Collection.</p>



<p></p>



<h3 class="wp-block-heading" id="aioseo-date-greater-than-query"><strong>Python </strong>&#8211; <strong>Mongo Date greater than query (&#8216;gt&#8217;)</strong></h3>



<p></p>



<h3 class="wp-block-heading" id="aioseo-define-the-date-for-the-query">Define the date for the query </h3>



<pre class="wp-block-code"><code>
start_date = datetime(2023, 1, 1)
</code></pre>



<p>OR</p>



<h3 class="wp-block-heading" id="aioseo-date-time-using-time-zone">Date time using time zone</h3>



<p></p>



<pre class="wp-block-code"><code>start_date = datetime(2023, 1, 1, tzinfo=timezone.utc)
</code></pre>



<h3 class="wp-block-heading" id="aioseo-define-the-filter">Define the filter </h3>



<p></p>



<pre class="wp-block-code"><code>filter =  {
         'DateAdded': {
                '$gt': start_date 

         }
  }


</code></pre>



<h3 class="wp-block-heading" id="aioseo-get-the-results">Get the results </h3>



<p></p>



<pre class="wp-block-code"><code>result = client&#91;'TheCodeBuzz']&#91;'Books'].find(filter=filter)

#print the results

for document in result: 

     print(document)</code></pre>



<p></p>



<p></p>



<p>Below is the complete code,</p>



<p></p>



<pre class="wp-block-code"><code>from datetime import datetime, tzinfo, timezone
from pymongo import MongoClient

# Define Python Mongo Connection

client = MongoClient('mongodb://localhost:27017/')
db = client&#91;'your_database']
collection = db&#91;'your_collection']

# define date for the query 

start_date = datetime(2023, 1, 1)

# define filter for the query 

filter =  {
         'DateAdded': {
                '$gt': start_date 

         }
  }

#execute query 

result = client&#91;'TheCodeBuzz']&#91;'Books'].find(filter=filter)

#print the results
for document in result: 

     print(document)
</code></pre>



<p></p>



<p></p>



<h4 class="wp-block-heading" id="aioseo-mongo-atlas-ui"><strong>Mongo Atlas UI</strong></h4>



<p></p>



<p>The above query produces the same result as indicated below using ATLAS UI,</p>



<p></p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="433" src="https://www.thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-1024x433.jpg" alt="python datetime mongodb format, python isodate, pymongo insert datetime now, mongodb date, " class="wp-image-13546" srcset="https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-1024x433.jpg 1024w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-300x127.jpg 300w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-768x325.jpg 768w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-1536x650.jpg 1536w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass-785x332.jpg 785w, https://thecodebuzz.com/wp-content/uploads/2020/12/MongoDB-Date-Range-query-examples-CLI-or-compass.jpg 1921w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<p><strong>Python </strong>&#8211; <strong>Mongo Date less than query (&#8216;lt&#8217;)</strong></p>



<p></p>



<pre class="wp-block-code"><code># define date for the query 

start_date = datetime(2023, 1, 1)

# define filter for the query 

filter =  {
         'DateAdded': {
                '$lt': start_date 

         }
  }</code></pre>



<p></p>



<p><strong>Python </strong>&#8211; <strong>Mongo Date less than and greater than date query </strong></p>



<p></p>



<p></p>



<pre class="wp-block-code"><code># define date for the query 

start_date = datetime(2023, 8, 1)
end_date = datetime(2024, 1, 1)

# define filter for the query 

filter =  {
         'DateAdded': {
                '$gte': start_date,
                '$lt': end_date

         }
  }

</code></pre>



<p>That&#8217;s all! Happy coding!</p>



<p></p>



<p>Does this help you fix your issue? </p>



<p></p>



<p>Do you have any better solutions or suggestions? Please sound off your comments below.</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/python-mongodb-date-time-query-pymongo/">Python – MongoDB Date Time query with examples</a> first appeared on <a href="https://thecodebuzz.com">TheCodeBuzz</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://thecodebuzz.com/python-mongodb-date-time-query-pymongo/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
