<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pavel Duchovny on Medium]]></title>
        <description><![CDATA[Stories by Pavel Duchovny on Medium]]></description>
        <link>https://medium.com/@pavel.duchovny?source=rss-c04e1d85e9af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*utQ-XqY9Z9HiaHMo</url>
            <title>Stories by Pavel Duchovny on Medium</title>
            <link>https://medium.com/@pavel.duchovny?source=rss-c04e1d85e9af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 23:16:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pavel.duchovny/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding MongoDB Role-based Access Control (RBAC) in Action: A Step-by-Step Guide]]></title>
            <link>https://medium.com/mongodb/understanding-mongodb-role-based-access-control-rbac-in-action-a-step-by-step-guide-8c679241f8b6?source=rss-c04e1d85e9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c679241f8b6</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[rbac]]></category>
            <dc:creator><![CDATA[Pavel Duchovny]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 09:18:22 GMT</pubDate>
            <atom:updated>2025-02-10T09:18:22.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2OcFLfgv1zINGZkc4C2EA.png" /></figure><p>Role-based access control (RBAC) is a critical security feature in MongoDB that enables fine-grained control over who can access or modify specific resources. It ensures that users have the permissions necessary for their role while restricting unauthorized actions, helping to secure sensitive data and maintain system integrity.</p><h3><strong>Why use RBAC?</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fk6QSs%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fk6QSs%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fk6QSs%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="290" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd1b330df08e4f9c560dc1e00f57b0ea/href">https://medium.com/media/fd1b330df08e4f9c560dc1e00f57b0ea/href</a></iframe><h3>RBAC components</h3><ol><li><strong>Roles</strong>: A combination of privileges and inheritance from other roles</li><li><strong>Privileges</strong>: Specific actions a role can perform on resources (e.g., read, write)</li><li><strong>Resources</strong>: Databases, collections, or specific operations within MongoDB</li></ol><h3>Built-in roles in MongoDB</h3><h3>MongoDB Atlas</h3><p><strong>Control panel roles examples:</strong></p><p>Atlas user roles define the actions Atlas users can perform in organizations, projects, or both.</p><ul><li><strong>Organization roles</strong>: Organization Owner, Member, Read-Only</li><li><strong>Project roles</strong>: Project Owner, Data Access Admin, Read/Write, Read-Only</li></ul><p>For a full list, see the documentation for <a href="https://www.mongodb.com/docs/atlas/reference/user-roles/?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_authz&amp;utm_term=pavel.duchovny">Atlas user roles</a>.</p><p><strong>Database user roles examples:</strong></p><p>Built-in database roles are assigned directly to database users and define a wide range of access permissions.</p><ul><li><strong>Roles</strong>:<strong> </strong><strong>atlasAdmin, </strong><strong>readWriteAnyDatabase, </strong><strong>readAnyDatabase</strong></li></ul><p>For a full list, see the documentation for <a href="https://www.mongodb.com/docs/atlas/mongodb-users-roles-and-privileges/?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_authz&amp;utm_term=pavel.duchovny">built-in roles and privileges</a>.</p><p><strong>Custom roles examples:</strong></p><p>Example: Create a custom database role in MongoDB Atlas for sales data access:</p><pre># Define a custom role with inherited privileges<br>atlas customDbRoles create &lt;role-name&gt; \<br>  --inheritedRole read@salesDB \<br>  --projectId {project_id}</pre><p>Explanation: This command creates a custom role in Atlas that inherits read access to the salesDB database, scoped to the specified project.</p><h3>On-premises MongoDB roles examples</h3><ul><li>Database user roles: read, readWrite.</li><li>Database administration roles: dbAdmin, dbOwner, userAdmin.</li><li>Cluster administration roles: clusterAdmin, clusterManager, clusterMonitor.</li></ul><p>Example: Assigning the readWrite role for application users:</p><pre>db.createUser({<br>  user: &quot;appUser&quot;,<br>  pwd: &quot;securePassword&quot;,<br>  roles: [ { role: &quot;readWrite&quot;, db: &quot;applicationDB&quot; } ]<br>})</pre><p>Explanation: This code creates a user named appUser with a readWrite role for the applicationDB database. The user can perform read and write operations within this database.</p><h3>Setting up RBAC: on-premises and Atlas</h3><h3>On-premises setup</h3><ol><li>Create an admin user:</li></ol><pre>use admin<br>db.createUser({<br>  user: &quot;adminUser&quot;,<br>  pwd: &quot;securePassword&quot;,<br>  roles: [<br>    { role: &quot;userAdminAnyDatabase&quot;, db: &quot;admin&quot; },<br>    { role: &quot;dbAdminAnyDatabase&quot;, db: &quot;admin&quot; }<br>  ]<br>})</pre><p><strong>Explanation</strong>: This creates an administrative user who can manage users (userAdminAnyDatabase) and databases (dbAdminAnyDatabase) across all databases.</p><p>2. Application-specific roles:</p><pre>db.createRole({<br>  role: &quot;applicationUser&quot;,<br>  privileges: [<br>    { resource: { db: &quot;appDB&quot;, collection: &quot;&quot; }, actions: [&quot;find&quot;, &quot;insert&quot;, &quot;update&quot;] }<br>  ],<br>  roles: []<br>})ja</pre><p><strong>Explanation</strong>: This defines a custom role called applicationUser with specific privileges (find, insert, update) on the appDB database. This role can then be assigned to users.</p><p>3. Assign the role to a user:</p><pre>db.createUser({<br>  user: &quot;orderProcessor&quot;,<br>  pwd: &quot;securePassword&quot;,<br>  roles: [ &quot;applicationUser&quot; ]<br>})</pre><p><strong>Explanation</strong>: This creates a user named orderProcessor and assigns them the applicationUser role, allowing them to perform specified actions.</p><h3>MongoDB Atlas setup</h3><ol><li>Create a database user:</li></ol><pre>atlas dbusers create \<br>  --username dataAdmin \<br>  --password &quot;securePassword&quot; \<br>  --role &quot;readWrite@admin&quot; \<br>--projectId your-project-id</pre><p><strong>Explanation</strong>: This command creates a database user in MongoDB Atlas with the readWrite role on the admin database within a specified project.</p><pre><br>atlas customDbRoles create analyticsReader \<br>  --privilege &#39;{ resource: { db: &quot;analytics&quot;, collection: &quot;&quot; }, actions: [&quot;find&quot;] }&#39; \<br>  --projectId your-project-id</pre><p><strong>Explanation</strong>: This creates a custom role in Atlas called analyticsReader, granting find privileges on the analytics database. This role can be assigned to analysts.</p><h3>Best practices for RBAC</h3><h3>MongoDB Atlas</h3><ol><li>Project-level access control:</li></ol><ul><li>Use project roles for team-based access.</li><li>Separate development and production environments.</li><li>Regularly audit project members.</li></ul><p>2. API access:</p><ul><li>Use programmatic API keys with appropriate roles.</li><li>Rotate API keys regularly and monitor their usage.</li></ul><h3>On-premises MongoDB</h3><ol><li>Role hierarchy:</li></ol><ul><li>Design roles based on job functions.</li><li>Use inheritance for consistency and simplicity.</li><li>Document role relationships for transparency.</li></ul><p>2. Monitoring and auditing:</p><ul><li>Enable audit logging for changes to roles and permissions.</li><li>Regularly review role assignments and update as necessary.</li></ul><h3>Common issues and troubleshooting</h3><ol><li>Insufficient privileges:</li></ol><ul><li>Verify that assigned roles include necessary privileges for the required operations.</li></ul><p>2. Audit logging configuration:</p><ul><li>Ensure that audit logging is enabled to monitor role changes and user actions.</li></ul><p>3. Role conflicts:</p><ul><li>Address conflicts where multiple roles have overlapping or contradictory permissions.</li></ul><h3>Conclusion</h3><p>Role-based access control (RBAC) in MongoDB is essential for securing sensitive data and maintaining control over database operations. By following the step-by-step setup and best practices outlined in this guide, you can implement RBAC effectively for both on-premises and Atlas environments.</p><h3>Frequently asked questions (FAQs)</h3><h3>How to grant a role to a user in MongoDB?</h3><p>To grant a role to a user, use the db.grantRolesToUser() method. Example:</p><pre>db.grantRolesToUser(<br>  &quot;userName&quot;,<br>  [ { role: &quot;readWrite&quot;, db: &quot;databaseName&quot; } ]<br>)</pre><h3>How to see roles in MongoDB?</h3><p>Use the db.getRoles() method to list all roles in the current database.</p><pre>db.getRoles({ showPrivileges: true })</pre><h3>What is a role in MongoDB?</h3><p>A role in MongoDB is a set of privileges defining the actions that a user can perform on specified resources.</p><h3>How do you authorize users in MongoDB?</h3><p>Users are authorized through authentication (e.g., SCRAM-SHA-256, Workload Identity Federation, x.509 certificates) and assigned roles that determine their privileges.</p><h3>How do I give access to a MongoDB database?</h3><p>To give access, create a user with the required roles for the database:</p><pre>db.createUser({<br>user: &quot;newUser&quot;,<br>pwd: &quot;password&quot;,<br>roles: [ { role: &quot;readWrite&quot;, db: &quot;targetDatabase&quot; } ]<br>})</pre><h3>How do I change the role in MongoDB?</h3><p>To modify a user’s role, first revoke the current roles and then grant new ones:</p><pre>// Revoke roles<br>db.revokeRolesFromUser(&quot;userName&quot;, [ &quot;oldRole&quot; ])<br>// Grant new roles<br>db.grantRolesToUser(&quot;userName&quot;, [ &quot;newRole&quot; ])</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c679241f8b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mongodb/understanding-mongodb-role-based-access-control-rbac-in-action-a-step-by-step-guide-8c679241f8b6">Understanding MongoDB Role-based Access Control (RBAC) in Action: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/mongodb">MongoDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MongoDB Authentication in Action: A Step by Step Guide]]></title>
            <link>https://medium.com/mongodb/understanding-mongodb-authentication-in-action-a-step-by-step-guide-e67c5655b023?source=rss-c04e1d85e9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/e67c5655b023</guid>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Pavel Duchovny]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 09:17:16 GMT</pubDate>
            <atom:updated>2025-02-10T09:17:16.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCYrzh2nJAYbtg1egFUTfA.png" /><figcaption>MongoDB Authentication</figcaption></figure><p>When it comes to securing your MongoDB instances, authentication plays a crucial role. Authentication is one of the most commonly used mechanisms for providing access control, especially when you want to ensure your data remains protected from unauthorized users. In this article, we’ll cover everything you need to know about implementing authentication in MongoDB, including best practices and a simple example to help you get started.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FYV0hE%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FYV0hE%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FYV0hE%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="149" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e9ef3a9496b29c4655aa60d0c6236ed/href">https://medium.com/media/2e9ef3a9496b29c4655aa60d0c6236ed/href</a></iframe><h3>What is authentication?</h3><p>Authentication is the process that confirms only the right people, services, and apps with the right permissions can get organizational resources. In MongoDB, this method allows users to authenticate before they can access or manipulate the data within a collection or a database. With MongoDB Enterprise by enabling authentication, you ensure that only verified users can interact with your data, which strengthens your security posture.</p><h3>Why authentication is important in MongoDB</h3><p>MongoDB, like any other database, can be vulnerable to attacks if not properly secured. By enabling authentication, you ensure:</p><ul><li><strong>Access control</strong>: Only authorized users can view or modify data.</li><li><strong>Data integrity</strong>: Prevent malicious users from altering or deleting important information.</li><li><strong>Auditability</strong>: Monitoring user activity is easier when every action is performed by authenticated users.</li></ul><h3>Setting up authentication for MongoDB (on-premises and Atlas)</h3><p>Below are the steps to set up authentication for your MongoDB instance. We will cover both MongoDB Enterprise Advance and Atlas-specific setups. Additionally, we will describe the different authentication types that MongoDB supports, including SCRAM-SHA-256, X.509, AWS IAM,Workload and Workforce Identity Federation , LDAP, and Kerberos.</p><h3>Supported authentication types in MongoDB</h3><h3>Authentication types</h3><p><strong>SCRAM-SHA-256:</strong> This is the default and simplest mechanism for MongoDB, providing secure authentication using salted challenge-response methods. For production deployments, we strongly recommend to consider one of the advanced types listed below.</p><h3>Advanced authentication types</h3><ul><li><strong>X.509</strong>: Certificate-based authentication that uses SSL/TLS certificates for verifying client identity; typically used in environments that require high security.</li><li><strong>Workforce Identity Federation</strong>: Allows users to integrate MongoDB Atlas with external identity providers (IdPs) like Okta or Azure AD for centralized access management and single sign-on (SSO).</li><li><strong>Workload Identity Federation</strong>: Workload Identity Federation lets your applications access MongoDB Atlas clusters using external programmatic identities such as Azure Service Principals, Azure Managed Identities and Google Service Accounts.</li><li><strong>AWS IAM (Atlas only)</strong>: Allows AWS apps/services to authenticate using their AWS Identity and Access Management roles, which is useful for integration with AWS services.</li><li><strong>LDAP</strong>: Allows integration with corporate directory services, enabling centralized management of user access across the organization.</li><li><strong>Kerberos (Enterprise Advanced only)</strong>: Provides a single sign-on experience and integrates with existing Kerberos-based authentication infrastructures, often used in enterprise environments.</li></ul><h3><strong>Enterprise Advanced MongoDB SCRAM authentication setup</strong></h3><ol><li>Create a user</li></ol><ul><li>Connect to your MongoDB instance using the Mongo Shell:</li></ul><pre>mongosh</pre><ul><li>Use the admin database:</li></ul><pre>use admin</pre><ul><li>Create a new user with a username and password:</li></ul><pre>db.createUser({<br>user: &quot;myUserAdmin&quot;,<br>pwd: &quot;mySecurePassword&quot;,<br>roles: [ { role: &quot;userAdminAnyDatabase&quot;, db: &quot;admin&quot; } ]<br>})</pre><p>2. Enable authentication</p><ul><li>Open the MongoDB configuration file (mongod.conf).</li><li>Set the authorization parameter to enabled in the security section:</li></ul><pre>security:<br>  authorization: enabled</pre><p>3. Restart MongoDB</p><ul><li>To apply the changes, restart the MongoDB server.</li></ul><pre>sudo systemctl restart mongod</pre><h3>Connecting with authentication enabled</h3><p>Once authentication is enabled, every connection attempt must provide credentials. Use the following command to connect:</p><pre>mongo -u myUserAdmin -p mySecurePassword --authenticationDatabase admin</pre><h3>Best practices for authentication in MongoDB</h3><ul><li>Strong passwords: Use strong, unique passwords for every user.</li><li>Least privilege: Assign roles that limit users to the minimal set of actions they need to perform.</li><li>IP allowlisting: Consider restricting access by allowing connections only from trusted IP addresses.</li><li>Use SCRAM for enhanced security: Instead of basic authentication, consider SCRAM (Salted Challenge Response Authentication Mechanism) for a more secure authentication method.</li></ul><h3>MongoDB Atlas setup</h3><h4>SCRAM-SHA-256</h4><ol><li>Create a database user</li></ol><ul><li>Log in to your MongoDB Atlas account.</li><li>Navigate to your cluster, and click on the <strong>Database Access</strong> tab.</li><li>Click <strong>Add New Database User</strong>.</li><li>Specify the username, password, and roles for the new user, and click <strong>Add User</strong>.</li></ul><p>2. Access-listing IP addresses</p><ul><li>In the <strong>Network Access</strong> tab, add your IP address or use 0.0.0.0/0 for open access (<strong>not recommended for production environments</strong>).</li></ul><p>3. Connecting to Atlas</p><ul><li>Use the connection string provided by Atlas, incorporating your username and password:</li></ul><pre>mongodb+srv://myUserAdmin:mySecurePassword@cluster0.mongodb.net/admin</pre><ul><li>Create a database SCRAM user in Atlas API</li></ul><pre>// Use Atlas Admin API<br>POST /api/atlas/v1.0/groups/{GROUP-ID}/databaseUsers<br>{<br> &quot;databaseName&quot;: &quot;admin&quot;,<br> &quot;username&quot;: &quot;myUser&quot;,<br> &quot;password&quot;: &quot;secure_password&quot;,<br> &quot;roles&quot;: [{<br>   &quot;roleName&quot;: &quot;readWrite&quot;,<br>   &quot;databaseName&quot;: &quot;myDatabase&quot;<br> }]<br>}</pre><h3>Best practices for authentication in Atlas</h3><ul><li>Identity Federation as standard:<strong> </strong>We recommend using the Identity Federation authentication mechanisms as standard for production secure authentication as they present modern and strong authentication.</li><li>Use strong passwords: When using passwords for Atlas database users, particularly in production, we highly recommend using our <a href="https://www.mongodb.com/products/integrations/hashicorp-vault">Atlas Secrets Engine integration with Hashicorp </a>vault to ensure strong passwords and rotations of the db users.</li><li>Secure network: Use a limited range of IPs that have access to the cluster and utilise Atlas VPC peering or/and private endpoints to best secure your cloud applications network to the cluster.</li></ul><h3>Compliance and global security standards</h3><p><a href="https://www.mongodb.com/products/platform/trust?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_auth&amp;utm_term=pavel.duchovny">MongoDB adheres to several global standards for information security</a>, ensuring that your data is stored and processed in a secure environment: <strong>ISO/IEC 27001:2022, ISO/IEC 27017:2015, ISO/IEC 27018:2019, ISO 9001:2015, SOC, CSA STAR, PCI DSS, HIPAA, HITRUST, VPAT (Section 508), GDPR, IRAP, TX-RAMP, TISAX, HDS</strong>. Authentication helps in ensuring compliance with these standards by enabling access control, maintaining data confidentiality, and providing secure access to cloud resources.</p><h3>Common issues and troubleshooting</h3><ul><li>Authentication failed errors: Double-check your credentialsAuthentication failed errors: Double-check your credentials (For Enterprise Advanced deployments ensure the authorization setting is enabled).</li><li>Role management: If a user cannot perform an action, verify that they have been assigned the necessary role.</li></ul><h3>Tutorial</h3><p>Use <a href="https://github.com/mongodb-developer/Security-Showcase/blob/main/notebooks/atlas_user_auth_and_rbac.ipynb?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_auth&amp;utm_term=pavel.duchovny">our notebook to play around</a> with basic and advanced MongoDB authentication features.</p><h3>Conclusion</h3><p>Authentication is a fundamental step in securing your MongoDB environment. By following the steps and best practices outlined in this guide, you can confidently set up and manage authentication, keeping your data safe from unauthorized access.</p><p>For more advanced security measures, like Authorization, Queryable Encryption, or Identity Federation, stay tuned for our upcoming articles on MongoDB security.</p><h3>FAQ: MongoDB Atlas security and features</h3><p><strong>1. Are MongoDB Atlas connections secure?</strong></p><p>MongoDB provides functionality to ensure that Atlas connections are secure.</p><p><strong>2. Is MongoDB Atlas private?</strong></p><p>MongoDB provides functionality that enables customers to ensure their data stays private and secure as well as to help them comply with regulatory and industry standard requirements.</p><p><strong>3. Does MongoDB Atlas offer encryption?</strong></p><p>Yes, MongoDB Atlas provides encryption for data in transit, in use, and at rest. Data is encrypted using industry-standard AES-256 encryption by default.</p><h3>FAQ: MongoDB authentication and compatibility</h3><p><strong>1. What kind of authentication is supported in MongoDB?</strong></p><p>MongoDB supports various authentication mechanisms, including:</p><ul><li>SCRAM (Salted Challenge Response Authentication Mechanism).</li><li>LDAP (Lightweight Directory Access Protocol) integration.</li><li>X.509 certificate-based authentication.</li><li>Kerberos.</li></ul><p>• AWS IAM authentication (for Atlas).</p><ul><li>Workload and Workforce Identity Federation.</li></ul><p><strong>2. How do you create user authentication in MongoDB?</strong></p><p>To create user authentication:</p><ul><li>Use the db.createUser() command to add a user with specific roles.</li><li>Define roles based on the required permissions (e.g., read, write).</li><li>For Self-Hosted deployments enable authentication by setting the — auth flag in the MongoDB configuration.</li></ul><p><strong>3. What is MongoDB compatible with?</strong></p><p>MongoDB is compatible with a wide range of platforms and tools, including:</p><ul><li>Multiple programming languages (e.g., Python, Java, Node.js, C#).</li><li>Cloud platforms (e.g., AWS, Azure, GCP).</li><li>Data visualization tools (e.g., Tableau, Power BI).</li><li>Various APIs and integration frameworks.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e67c5655b023" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mongodb/understanding-mongodb-authentication-in-action-a-step-by-step-guide-e67c5655b023">Understanding MongoDB Authentication in Action: A Step by Step Guide</a> was originally published in <a href="https://medium.com/mongodb">MongoDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MongoDB Queryable Encryption in Action: A Step-by-Step Guide]]></title>
            <link>https://medium.com/mongodb/understanding-mongodb-queryable-encryption-in-action-a-step-by-step-guide-bfa299ac2c86?source=rss-c04e1d85e9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfa299ac2c86</guid>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Pavel Duchovny]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 07:18:01 GMT</pubDate>
            <atom:updated>2025-02-06T07:18:01.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JvMJWbXUvpRuqNbKIK2Xg.png" /></figure><p>When it comes to securing sensitive data in your MongoDB instances, Queryable Encryption offers a powerful solution. Unlike traditional encryption methods where data must be decrypted before querying, Queryable Encryption allows you to run queries directly on encrypted data, significantly enhancing security and maintaining functionality. In this article, we’ll cover everything you need to know about implementing Queryable Encryption in MongoDB, including its benefits, setup steps for both on-premise and Atlas deployments, and best practices to help you get started.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fvhh85%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fvhh85%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fvhh85%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="165" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d13f37388ddf5c1d1f00bc767628e7d/href">https://medium.com/media/3d13f37388ddf5c1d1f00bc767628e7d/href</a></iframe><h3>What is Queryable Encryption?</h3><p>Queryable Encryption is a groundbreaking technology that allows you to run specific queries on encrypted data without the need to decrypt it on the server. In MongoDB, this means sensitive data can remain encrypted throughout its lifecycle — at rest, in transit, and even during query processing. By enabling Queryable Encryption, you significantly reduce the attack surface by minimizing the exposure of plaintext data, even to authorized database administrators. This strengthens your security posture and helps meet stringent compliance requirements.</p><h3>Why is Queryable Encryption important in MongoDB?</h3><p>MongoDB, while offering various security features, can benefit significantly from Queryable Encryption for scenarios involving highly sensitive data. By implementing it, you ensure:</p><ul><li>Enhanced data protection: Sensitive data remains encrypted even when it is being processed on the database side, minimizing the risk of exposure in case of a security breach or unauthorized access.</li><li>Compliance with regulations: It helps meet stringent data privacy regulations like GDPR, HIPAA, and others that mandate strong encryption and control over sensitive information.</li><li>Reduced insider threat: Even database administrators or authorized personnel with access to the database infrastructure cannot see the plaintext data without the appropriate decryption keys managed outside of the database.</li><li>Maintain functionality: Unlike traditional encryption, where data needs to be decrypted for querying, Queryable Encryption allows you to perform specific types of queries directly on the encrypted data, preserving application functionality.</li></ul><h3>Setting up Queryable Encryption for MongoDB (on-prem and Atlas)</h3><p>Below are the steps to set up Queryable Encryption for your MongoDB instance. We will cover both MongoDB on-prem and Atlas-specific setups. Additionally, we will describe key concepts like key management systems (KMS) and client-side encryption.</p><h3>Key concepts in Queryable Encryption</h3><ul><li>Key management system: KMS is a secure system for managing encryption keys. MongoDB Queryable Encryption relies on either local keys/on-premises vaults like Hashicorp, or external KMS providers like AWS KMS, Azure Key Vault, or Google Cloud KMS to store and manage the cryptographic keys.</li><li>Encryption on field level basis: Encryption and decryption operations are performed on the client-side application before data is sent to or retrieved from the MongoDB server. This ensures that the server only handles encrypted data.</li><li>Encryption schema: This defines which fields in your documents need to be encrypted and specifies the type of encryption to be used for each field, influencing the types of queries that can be performed on that field.</li></ul><h3>On-prem MongoDB Queryable Encryption setup</h3><ol><li>Configure a key management system:</li></ol><ul><li>Choose a supported KMS provider (AWS KMS, Azure Key Vault, Google Cloud KMS), or configure an on-premises key provider.</li><li>Create a customer managed key (CMK) within your chosen KMS. Grant your MongoDB server or application the necessary permissions to access the CMK.</li></ul><p>2. Install MongoDB Enterprise edition: Automatic Encryption is a feature of MongoDB Enterprise Edition. (Community edition users must use Queryable Encryption’s explicit encryption features.) Ensure you have the correct version installed for the query types you need to support. Alternatively, create a MongoDB Atlas cluster: Ensure you are using a cluster version that <a href="https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/compatibility/?tck=mongodb_ai_chatbot#queryable-encryption-compatibility?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_qe&amp;utm_term=pavel.duchovny">supports Queryable Encryption</a>; different versions might support different query operators.</p><h3>Configure Queryable Encryption</h3><ul><li>Install the MongoDB driver that supports Queryable Encryption for your chosen programming language (e.g., <em>mongodb</em> Python driver version 4.1 or later).</li><li>Install the needed <a href="https://www.mongodb.com/docs/manual/core/queryable-encryption/install-library/?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_qe&amp;utm_term=pavel.duchovny">prerequisites</a> and the Automatic Encryption Shared Library for your operating system.</li><li>Configure the client application to use automatic encryption settings. This involves specifying the KMS provider, KMS credentials, and the encryption schema.</li></ul><pre>from pymongo import MongoClient<br>from pymongo.encryption import Algorithm, ClientEncryption, QueryType<br>from pymongo.encryption_options import AutoEncryptionOpts<br>from bson.codec_options import CodecOptions<br>from bson import json_util<br><br>crypt_shared_lib_path = &quot;&lt;YOUR PATH TO YOUR CRYPTD LIBRARY&gt;&quot;<br><br># KMS configuration (example for local)<br>local_master_key = os.urandom(96)<br>kms_providers = {&quot;local&quot;: {&quot;key&quot;: local_master_key}}<br>key_vault_namespace = &quot;encryption.__keyVault&quot;<br>kms_provider_name=&quot;local&quot;<br>key_vault_database_name = &quot;encryption&quot;<br>key_vault_collection_name = &quot;__keyVault&quot;<br>key_vault_namespace = f&quot;{key_vault_database_name}.{key_vault_collection_name}&quot;<br>encrypted_database_name = &quot;medicalRecords&quot;<br>encrypted_collection_name = &quot;patients&quot;<br><br><br># Auto encryption opts<br>auto_encryption_options = AutoEncryptionOpts(<br>kms_providers,<br>key_vault_namespace,<br>crypt_shared_lib_path=crypt_shared_lib_path<br>)<br><br># Create encrypted client<br>encrypted_client = MongoClient(<br>&quot;mongodb://&lt;host&gt;:&lt;port&gt;&quot;, auto_encryption_opts=auto_encryption_options)<br><br><br># Define the client encryption settings<br>client_encryption = ClientEncryption(<br>kms_providers=kms_providers,<br>key_vault_namespace=key_vault_namespace,<br>key_vault_client=encrypted_client,<br>codec_options=CodecOptions()<br>)</pre><h4>Define the encryption schema:</h4><ul><li>Create a JSON schema that specifies which fields to encrypt and the type of encryption to use. The encryption type determines the query operators you can use on the encrypted field.</li></ul><pre>encrypted_fields_map = {<br>&quot;fields&quot;: [<br>    {<br>        &quot;path&quot;: &quot;sensitiveField&quot;,<br>        &quot;bsonType&quot;: &quot;string&quot;,<br>        &quot;queries&quot;: [{&quot;queryType&quot;: &quot;equality&quot;}] # potentially &#39;range&#39;<br>    }<br>]<br>}</pre><ul><li>queryType: This defines the type of query supported for an encrypted field, which can be either “equality” for exact matches or “range” for comparing numeric values. You can also specify no query type if you only need non-deterministic encryption for the given field.</li><li>Create an encrypted collection:<strong> </strong>When creating a collection, specify the needed components:</li></ul><pre>client_encryption.create_encrypted_collection(<br>encrypted_client[encrypted_database_name],<br>encrypted_collection_name,<br>encrypted_fields_map,<br>kms_provider_name,<br>{},<br>)</pre><p>Define the encryption schema:</p><ul><li>You can define the encryption schema programmatically within your application code, similar to the setup.</li></ul><p>Create an encrypted collection:</p><ul><li>You can create collections directly through the mongosh shell or programmatically. Ensure that your client application is configured with the encryption schema for automatic encryption to take place.</li></ul><h3>Connecting with Queryable Encryption enabled</h3><p>Once Queryable Encryption is set up, your application interacts with the database using the configured MongoDB driver. The driver handles the encryption and decryption of specified fields transparently based on the encryption schema.</p><p>For example, inserting a document with a field marked for encryption will automatically encrypt that field before sending it to the MongoDB server.</p><h3>Using encrypted fields</h3><p>When working with Queryable Encryption, your application code interacts with data as if it were not encrypted. The MongoDB driver handles the encryption and decryption transparently.</p><pre>from pymongo import MongoClient<br><br># ... (MongoClient setup with encryption options as shown above) ...<br><br>encrypted_collection = encrypted_client[encrypted_database_name][encrypted_collection_name]<br><br># Insert a document (encryption happens automatically)<br>document_to_insert = {&quot;sensitiveField&quot;: &quot;secret value&quot;, &quot;otherField&quot;: &quot;some data&quot;}<br>encrypted_collection.insert_one(document_to_insert)<br><br># Query using queryable encryption<br>query_result = encrypted_collection.find_one({&quot;sensitiveField&quot;: &quot;secret value&quot;})<br>print(query_result)</pre><h3>Supported query types</h3><p>Queryable Encryption in MongoDB supports different types of queries depending on the encryption algorithm used:</p><h3>Equality queries</h3><ul><li>Supported with deterministic encryption</li><li>Exact match comparisons using $eq operator</li></ul><blockquote>Example:</blockquote><blockquote>{“encryptedField”: “exactValue”}</blockquote><ul><li>For more information, see <a href="https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/supported-operations/?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_qe&amp;utm_term=pavel.duchovny">documentation</a>.</li></ul><h3>Range queries</h3><ul><li>Available for range-queryable encrypted fields</li><li>Supports operators like <em>$gt, $gte, $lt, $lte</em></li></ul><blockquote>Example:</blockquote><blockquote>{&quot;encryptedField&quot;: {&quot;$gt&quot;: &quot;value&quot;}}</blockquote><h3>Limitations</h3><ul><li>See the following <a href="https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/limitations/?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_qe&amp;utm_term=pavel.duchovny">documentation</a>.</li></ul><h3>Best practices for Queryable Encryption in MongoDB</h3><ul><li>Securely manage KMS credentials: Protect your KMS access keys and credentials diligently. Use best practices for secret management.</li><li>Understand performance implications: Queryable Encryption involves additional resources for indexing and storage on the server side. Test and optimize your application accordingly. Having said that, tune the relevant parameters and <a href="https://www.mongodb.com/docs/manual/core/queryable-encryption/fundamentals/encrypt-and-query/?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_qe&amp;utm_term=pavel.duchovny">document design</a> for best performance.</li><li>Principle of least privilege: Grant only the necessary permissions to access encryption keys.</li><li>Monitor and audit<strong>:</strong> Monitor access to your KMS and audit encryption configurations.</li></ul><h3>Compliance and global security standards</h3><p>Implementing Queryable Encryption helps organizations meet various compliance requirements and global security standards by ensuring that sensitive data remains protected throughout its lifecycle. This aligns with the principles of data minimization and data protection by design.</p><ul><li>Schema defined in your client application matches the schema used for the collection.</li></ul><h3>Tutorial</h3><p>For hands-on practice with Queryable Encryption concepts, refer to our new <a href="https://mongodb-developer.github.io/security-basics-lab?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_qe&amp;utm_term=pavel.duchovny">lab for security basics</a> which has a step-by-step guide with practical interactive notebooks.</p><h3>Conclusion</h3><p>Queryable Encryption represents a significant advancement in data security for MongoDB. By enabling you to query encrypted data without decryption on the server, it offers a robust solution for protecting sensitive information while maintaining application functionality. By following the steps and best practices outlined in this guide, you can confidently implement Queryable Encryption in your MongoDB deployments and strengthen your overall security posture.</p><h3>FAQ: MongoDB Queryable Encryption</h3><ol><li><strong>Is Queryable Encryption available in MongoDB Community Edition?</strong></li></ol><p>Yes, but automatic encryption is only available in EA and Atlas.</p><p><strong>2. What types of queries are supported with Queryable Encryption?</strong></p><p>With Queryable Encryption, you can currently perform equality and range queries on encrypted fields. For more information, see the <a href="https://www.mongodb.com/docs/manual/core/queryable-encryption/reference/supported-operations/?utm_campaign=devrel&amp;utm_source=medium&amp;utm_medium=medium_article&amp;utm_content=bp_qe&amp;utm_term=pavel.duchovny">documentation</a>.</p><p><strong>3. Do I need to change my application code significantly to use Queryable Encryption?</strong></p><p>The MongoDB driver handles most of the encryption and decryption automatically based on the configured encryption schema. However, you need to create an encrypted collection. Configure the client with KMS details and the schema.</p><p><strong>4. Is there a performance overhead with Queryable Encryption?</strong></p><p>Yes, there is a performance overhead due to creation of encrypted index structures. Good data modeling and parameter tuning makes the performance impact practical for most real-world applications.</p><p><strong>5. Can I use Queryable Encryption with MongoDB Atlas Search?</strong></p><p>Currently, Queryable Encryption is not directly compatible with MongoDB Atlas Search.</p><p><strong>6. What happens if I lose my encryption keys?</strong></p><p>If you lose your encryption keys, the encrypted data will be unrecoverable. Secure key management is critical when using Queryable Encryption.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfa299ac2c86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mongodb/understanding-mongodb-queryable-encryption-in-action-a-step-by-step-guide-bfa299ac2c86">Understanding MongoDB Queryable Encryption in Action: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/mongodb">MongoDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB, A Case Study in Bitemporal Data Management: Addressing Challenges in High-Frequency…]]></title>
            <link>https://medium.com/mongodb/mongodb-a-case-study-in-bitemporal-data-management-addressing-challenges-in-high-frequency-2417419f1500?source=rss-c04e1d85e9af------2</link>
            <guid isPermaLink="false">https://medium.com/p/2417419f1500</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[real-time-data]]></category>
            <dc:creator><![CDATA[Pavel Duchovny]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 11:44:35 GMT</pubDate>
            <atom:updated>2024-11-26T11:44:35.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>MongoDB, A Case Study in Bitemporal Data Management: Addressing Challenges in High-Frequency Financial Data Systems</h3><p>The use of bitemporal data models is critical in industries like finance, where understanding both the history of data and its changes is vital. This case study delves into the challenges faced by a financial institution managing high-frequency trading and market risk data and how a bitemporal data solution addressed these challenges.</p><figure><img alt="Bitemporal data for financial operations" src="https://cdn-images-1.medium.com/max/896/1*io_7Jm-HXDmJjVVsH2vT6A.png" /></figure><h3>What is Bitemporal Data?</h3><p>Bitemporal data refers to data that captures two distinct time aspects: <strong>valid time</strong> and <strong>transaction time</strong>. Valid time represents the period during which the data is relevant in the real world, while transaction time represents when the data was stored or modified in the database. This dual-timeline approach is crucial for accurately tracking historical data changes, allowing both the historical state of the data and when changes occurred to be preserved.</p><h3>Problem Overview</h3><p>The financial institution in question used a real-time risk management platform, QStack, for managing trading risks for both clients and internal operations. Their system used Cassandra for storing historical market data, but they faced several challenges:</p><ul><li><strong>Read Latency Issues</strong>: The platform struggled with large-range queries, especially for data spanning more than one year, which impacted their ability to provide quick risk assessments.</li><li><strong>Scaling Challenges</strong>: On-premises provisioning limitations restricted the infrastructure required to manage growing workloads, causing delays in calculations.</li><li><strong>Operational Bottlenecks</strong>: Frequent regulatory breaches led to developer resources being diverted to handle support issues instead of focusing on innovation and new feature development.</li><li><strong>Data Model Limitations</strong>: Cassandra’s limitations impacted replication and efficient data retrieval, particularly when managing time-sensitive data critical to regulatory compliance and decision-making.</li></ul><h3>The Bitemporal Data Solution</h3><p>To address these challenges, the team explored implementing a bitemporal model using MongoDB. The bitemporal model allowed them to track two versions of the same data:</p><ol><li><strong>Valid Time</strong>: The period during which data is valid in the business domain. In the data model, this corresponds to the validDate field.</li><li><strong>Transaction Time</strong>: The point in time when the data was recorded in the system. In the model, this is represented by the transactionTime field.</li></ol><h3>Process of Implementing the Solution</h3><p>The data was stored with a combination of valid-time and transaction-time timestamps to ensure both historical versions and changes over time could be captured. Each version of the data had its own record, allowing for easy versioning and faster range queries.</p><h3>Time series collection for optimized temporal data operations and storage</h3><p>To enhance the efficiency of querying and data management, a <a href="https://www.mongodb.com/docs/v8.0/core/timeseries-collections/#time-series-collections?utm_campaign=devrel&amp;utm_term=pavel.duchovny&amp;medium=article&amp;content=insights_bitemporal">timeseries collection</a> was created. Time series collections in MongoDB are optimized to store, manage, and analyze sequential time-stamped data. In these collections, data from the same source and similar time are stored together on disk. The transactionTime field was selected as the time field for grouping the data points. This time series collection captures changes over time effectively, making it particularly suitable for temporal data operations. Below is the code for creating the timeseries collection:</p><pre> db.createCollection(<br>    &quot;bitemporal_data&quot;,<br>    {<br>      timeseries: {<br>        timeField: &quot;transactionTime&quot;,<br>        metaField: &quot;metadata&quot;,<br>        granularity: &quot;seconds&quot;<br>      }<br>    }<br>  );</pre><p>Additionally, a secondary index on the validDate field was added to facilitate efficient range-based lookups and retrievals of data versions based on business dates. The combination of the transactionTime(Transaction Time) as the primary time-based index and validDate(Valid Time) as a secondary index ensures that both point-in-time queries and historical analysis can be performed efficiently.</p><h3>Schema considerations</h3><p>Multiple schema options were evaluated, such as versioning patterns, bucketing patterns, and timeseries collections:</p><ul><li><strong>Version Pattern</strong>: This was the simplest option, storing each change in a separate document. Although it led to some data duplication, it provided flexibility with indexing and querying.</li><li><strong>Bucketing Pattern</strong>: Data was bucketed by business dates, helping to avoid bloated documents and enabling efficient range queries, especially when indexed properly.</li><li><strong>Timeseries Collection</strong>: MongoDB’s timeseries capabilities were used for optimizing data that needed to be stored in temporal order, with metadata for more granular querying.</li></ul><h4>Data Modeling Examples</h4><p>Version Pattern Example Document</p><pre>{<br>   &quot;validDate&quot;: ISODate(&quot;2019-01-01T00:00:00.000Z&quot;),<br>   &quot;location&quot;: &quot;New York&quot;,<br>   &quot;alias&quot;: &quot;QStackTrader001&quot;,<br>   &quot;groups&quot;: [&quot;Risk&quot;, &quot;Market Data&quot;],<br>   &quot;transactionTime&quot;: ISODate(&quot;2019-05-01T00:00:00.000Z&quot;),<br>   &quot;value&quot;: {<br>       &quot;risk_score&quot;: 87,<br>       &quot;market_value&quot;: 1000000<br>   },<br>   &quot;annotation&quot;: {<br>       &quot;comment&quot;: &quot;Initial risk assessment&quot;,<br>       &quot;analyst&quot;: &quot;Jane Doe&quot;<br>   }<br>}</pre><p>Bucketing Pattern Example Document</p><pre>{<br>   &quot;validDate&quot;: ISODate(&quot;2019-01-01T00:00:00.000Z&quot;),<br>   &quot;location&quot;: &quot;London&quot;,<br>   &quot;alias&quot;: &quot;QStackTrader002&quot;,<br>   &quot;groups&quot;: &quot;Market Analytics&quot;,<br>   &quot;data&quot;: [<br>       {<br>           &quot;transactionTime&quot;: ISODate(&quot;2019-01-01T00:00:00.000Z&quot;),<br>           &quot;value&quot;: {<br>               &quot;risk_score&quot;: 72,<br>               &quot;market_value&quot;: 1200000<br>           },<br>           &quot;annotation&quot;: {<br>               &quot;comment&quot;: &quot;Daily assessment&quot;,<br>               &quot;analyst&quot;: &quot;John Smith&quot;<br>           }<br>       },<br>       {<br>           &quot;transactionTime&quot;: ISODate(&quot;2019-05-01T00:00:00.000Z&quot;),<br>           &quot;value&quot;: {<br>               &quot;risk_score&quot;: 75,<br>               &quot;market_value&quot;: 1250000<br>           },<br>           &quot;annotation&quot;: {<br>               &quot;comment&quot;: &quot;Updated risk score after market change&quot;,<br>               &quot;analyst&quot;: &quot;John Smith&quot;<br>           }<br>       }<br>   ]<br>}</pre><p>Timeseries Collection Example Document</p><pre>{<br>   &quot;transactionTime&quot;: ISODate(&quot;2019-05-01T00:00:00.000Z&quot;),<br>   &quot;metadata&quot;: {<br>       &quot;location&quot;: &quot;Singapore&quot;,<br>       &quot;alias&quot;: &quot;QStackTrader003&quot;,<br>       &quot;groups&quot;: &quot;APAC Market Data&quot;<br>   },<br>   &quot;validDate&quot;: ISODate(&quot;2019-01-01T00:00:00.000Z&quot;),<br>   &quot;value&quot;: {<br>       &quot;risk_score&quot;: 81,<br>       &quot;market_value&quot;: 900000<br>   },<br>   &quot;annotation&quot;: {<br>       &quot;comment&quot;: &quot;Quarterly update&quot;,<br>       &quot;analyst&quot;: &quot;Alice Wong&quot;<br>   }<br>}</pre><h3>Suggested Data Model</h3><p>The suggested model was a combination of using the timeseries collection built-in bucketing capability and the ability to represent documents as individual data points, which is similar to a versioning pattern. However, it was ultimately decided to use the transactionTime as the timeField to avoid backfills and mitigate some of the antipatterns commonly associated with time series collections. Since data in time series collections are bucketed by date and metadata fields, choosing validDate as the timeField for bucketing could have led to complications when writing to closed buckets (historical buckets), especially if changes or updates were needed for historical data. This would require reopening and rewriting closed buckets, which is both resource-intensive and prone to errors, making transactionTime a more efficient option. The data model was optimized for inserting new data ahead rather than backfilling, making transactionTime a more suitable choice for managing data changes effectively.</p><h3>Query and Index Examples</h3><p><strong>Indexes for Efficient Querying</strong></p><p>This index on the timeseries collection is crucial for optimizing both historical (validDate) and real-time (transactionTime) queries. It enables efficient filtering and sorting of data based on key metadata attributes (alias, groups) and temporal fields, thus making it possible to handle a large volume of time-sensitive data with minimal latency.</p><pre>db.bitemporal_data.createIndex({ &quot;validDate&quot;: 1, <br>                                 &quot;metadata.alias&quot;: 1, <br>                                 &quot;metadata.groups&quot;: 1, <br>                                 &quot;transactionTime&quot;: -1 });</pre><p><strong>Example Queries</strong></p><ul><li><strong>Retrieve Latest Version by Alias and Date</strong></li></ul><p>This query is designed to find the latest version of data for a specific alias and business date. Sorting by transactionTime in descending order ensures that the most recent version is retrieved, and using limit(1) guarantees efficient retrieval without scanning unnecessary documents.</p><pre>db.bitemporal_data.find({<br>   &quot;validDate&quot;: ISODate(&quot;2019-01-01T00:00:00.000Z&quot;),<br>   &quot;metadata.alias&quot;: &quot;QStackTrader001&quot;,<br>   &quot;metadata.group&quot; : &quot;APAC Market Data&quot;<br>}).sort({ &quot;transactionTime&quot;: -1 }).limit(1);</pre><p><strong>Bucketing Pattern query</strong></p><ul><li><strong>Index</strong></li></ul><p>These indexes are designed to improve the efficiency of queries involving both the business date (validDate) and the classification fields (alias and groups). By indexing both transactionTime and validDate, the model ensures that lookups can quickly find the correct version of the data for a specific date range, optimizing for both historical analysis and recent data queries.</p><pre>db.bitemporal_data.createIndex({ &quot;metadata.alias&quot;: 1,<br>                                 &quot;metadata.groups&quot;: 1, <br>                                 &quot;transactionTime&quot;: -1, <br>                                 &quot;validDate&quot;: 1 });</pre><p>This aggregation helps efficiently extract the latest version of the data for each business date within a range. By using $sort and $addFields, the query reduces the data points to the most recent entry, optimizing the performance of data retrieval for time series analysis while minimizing resource usage.</p><pre>db.bitemporal_data.aggregate([<br>   {<br>     $match: {<br>       &quot;validDate&quot;: {<br>         $gte: ISODate(&quot;2000-01-01T00:00:00.000Z&quot;),<br>         $lte: ISODate(&quot;2030-05-01T00:00:00.000Z&quot;)<br>       },<br>       &quot;alias&quot;: &quot;est&quot;,<br>       &quot;groups&quot;: &quot;Market Analytics&quot;,<br>       &quot;transactionTime&quot;: {<br>         $lte: ISODate(&quot;2021-01-01&quot;)<br>       }<br>     }<br>   },<br>   { $sort: { &quot;data.asof&quot;: -1 } },<br>   { $addFields: { data: { $first: { $sortArray: { input: &quot;$data&quot;, sortBy: { asof: -1 } } } } } }<br>]);</pre><h3>Moving to MongoDB Atlas</h3><p>The decision to move to MongoDB Atlas helped address several key challenges faced by the financial institution:</p><ul><li><strong>Scaling Challenges</strong>: MongoDB Atlas provided a fully managed, cloud-native platform with auto-scaling capabilities. This eliminated the constraints of on-premises provisioning, allowing the infrastructure to scale dynamically in response to growing workloads. This flexibility ensured that risk calculations could be handled without delays, even during peak data influx.</li><li><strong>Operational Bottlenecks</strong>: MongoDB Atlas enabled a significant reduction in support-related overhead by leveraging its built-in automation, security, and compliance features. The frequent regulatory breaches were addressed by improved auditing and automated security protocols, allowing developer resources to shift their focus back to innovation and new feature development instead of firefighting support issues.</li></ul><h3>Solution Benefits</h3><ul><li><strong>Timeseries Collection</strong>: The chosen data model leveraged transactionTime as the timeField to efficiently manage data changes while avoiding backfill issues and mitigating common timeseries antipatterns.</li><li><strong>Reduced Latency</strong>: By optimizing queries with secondary indexes and using a combination of valid-time and transaction-time timestamps, the bitemporal solution reduced read latency significantly.</li><li><strong>Scalability</strong>: Moving to a cloud-native platform allowed the team to take advantage of auto-scaling capabilities. MongoDB’s ability to replicate data across multiple regions improved both performance and fault tolerance.</li><li><strong>Regulatory Compliance</strong>: The bitemporal model made it easier to comply with regulations by keeping a clear audit trail of data changes, thereby reducing the number of breaches and associated penalties. In financial systems, regulatory compliance often requires maintaining an accurate history of all data changes, including both the validity of the data in a business context (valid time) and the actual time when the data was recorded or changed (transaction time). By using a bitemporal approach, the platform ensured that any modifications to data were fully traceable, providing regulators with a complete version history for auditing purposes. MongoDB’s ability to store both valid-time and transaction-time information in a structured manner allowed for precise reporting and adherence to compliance standards. Furthermore, the automation capabilities provided by MongoDB Atlas — including built-in backup, encryption, and audit logs — further helped in reducing operational risks and maintaining data integrity, ensuring full alignment with regulatory requirements.</li></ul><h3>Lessons Learned</h3><ol><li><strong>Schema Design is Key</strong>: Choosing the right schema design is crucial in bitemporal data models. A mix of bucketing and versioning helped the team achieve balance between flexibility and performance.</li><li><strong>Avoiding Antipatterns</strong>: Storing large documents or too many small redundant documents resulted in inefficiencies. Designing for optimal data retrieval by balancing document size was critical.</li><li><strong>Iterative Testing</strong>: Implementing the solution involves iterations with different index and query optimizations to minimize latency while ensuring data integrity.</li></ol><h3>Conclusion</h3><p>Implementing a bitemporal data model for the QStack risk management platform allowed the financial institution to overcome significant operational and technical challenges. By leveraging cloud capabilities and an effective data model, they achieved scalability, reduced latency, and ensured better compliance — all while improving developer productivity by minimizing support overhead.</p><h3>Key Takeaways</h3><ul><li>Bitemporal models can significantly improve compliance and operational efficiency in finance.</li><li>Careful schema design and indexing are key to maximizing the benefits of bitemporal data.</li><li>Moving to cloud infrastructure with MongoDB can provide flexibility and scalability that is difficult to achieve on-premises.</li></ul><p>Do you want to know more? Check out our <a href="https://www.mongodb.com/developer/?utm_campaign=devrel&amp;utm_source=third-party&amp;utm_medium=cta&amp;utm_term=pavel.duchovny">Developer Center</a> or try <a href="https://www.mongodb.com/cloud/atlas/register?utm_campaign=devrel&amp;utm_source=third-party&amp;utm_medium=cta&amp;utm_term=pavel.duchovny">Atlas for free</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2417419f1500" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mongodb/mongodb-a-case-study-in-bitemporal-data-management-addressing-challenges-in-high-frequency-2417419f1500">MongoDB, A Case Study in Bitemporal Data Management: Addressing Challenges in High-Frequency…</a> was originally published in <a href="https://medium.com/mongodb">MongoDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>