<?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 Paoletti Alessia on Medium]]></title>
        <description><![CDATA[Stories by Paoletti Alessia on Medium]]></description>
        <link>https://medium.com/@paoletti.alessia?source=rss-8ecce4f15a4b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SRSdhNz2DNo3DuK0</url>
            <title>Stories by Paoletti Alessia on Medium</title>
            <link>https://medium.com/@paoletti.alessia?source=rss-8ecce4f15a4b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:35:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paoletti.alessia/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[AI Agents Need Identities Too: Passkeys, OAuth 2.1, and Zero Trust for AI-First Applications]]></title>
            <link>https://medium.com/data-reply-it-datatech/ai-agents-need-identities-too-passkeys-oauth-2-1-and-zero-trust-for-ai-first-applications-7937e14dd762?source=rss-8ecce4f15a4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7937e14dd762</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Paoletti Alessia]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 08:11:02 GMT</pubDate>
            <atom:updated>2026-10-01T08:11:02.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2yDaBG3uKLGs8FqgLU7SQ.png" /></figure><p>In just a few seconds, an AI agent with the wrong permissions can turn a routine task into a <strong>production incident</strong>. In one widely <a href="https://www.theguardian.com/technology/2026/apr/29/claude-ai-deletes-firm-database">reported case</a>, an AI coding agent reportedly deleted a company’s production database and backups, causing a major outage and exposing a deeper problem.</p><p>In AI-first systems, the real risk is not only what the model can generate, but what it is allowed to execute.</p><p>As AI agents evolve from passive assistants into true active operators, security can no longer stop at a simple login. We now need to think in terms of:</p><ul><li>Identity — who (or what) is acting</li><li>Delegation — on whose behalf the agent operates</li><li>Continuous verification — ongoing control, not just at initial access</li><li>Privilege boundaries — what it is allowed to do</li></ul><p>In other words: the user is only the starting point. <strong>The agent also needs its own identity</strong>, and the system must be able to define what that agent can do, for how long, and under which conditions.</p><h3>Why password-based security and traditional MFA are no longer enough</h3><p>The classic security model was designed for a world where a human logs in, does something manually, and logs out. Passwords, one-time codes, and push-based MFA were built to protect that flow. But AI agents break that assumption.</p><p>The first problem is that <strong>passwords are still weak in practice</strong>. They get reused, guessed, phished, leaked, and stolen through credential stuffing. Even traditional MFA is not a complete answer. SMS codes can be intercepted or abused, and push notifications can lead to approval fatigue, where users click “<em>yes</em>” just to make the prompt disappear. Those mechanisms may reduce risk, but they do not create a truly phishing-resistant identity layer.</p><p>The<strong> second problem is delegation</strong>. When an AI agent acts on behalf of a user, the question is no longer only “who logged in?” but “who is acting now?” If the same credential or session token is reused everywhere, the boundary between the human and the agent disappears.</p><h3>Agents as first-class principals</h3><p>In traditional systems, identities were easy to categorize: a human user, a service account, maybe an admin. AI agents change that by creating a new class of actor. They are not exactly human users, and they are not just background services either. They are <strong>autonomous or semi-autonomous entities that can reason, call tools, execute actions, and chain operations together. </strong>That means they need their own identity model.</p><p>An agent should be treated as a first-class principal with:</p><ul><li>its own identity</li><li>its own lifecycle</li><li>its own permission set</li><li>its own audit trail</li><li>its own revocation path</li></ul><p>If an agent acts under the same credentials as the user, you lose attribution. If it acts under a distinct delegated identity, you can answer critical questions later: which agent executed this action? On whose behalf? With what scope? At what time? Under what policy conditions?</p><p>That distinction is crucial when something goes wrong.</p><h3>Passkeys as the foundation for human authentication</h3><p>Before delegation can happen, the human identity itself needs to be verified with something stronger than a password. This is where passkeys come in.</p><p>A <strong>passkey </strong>is a credential based on public-key cryptography, <strong>generated and stored on the user’s device rather than on a server</strong>. When a passkey is created, the device generates a key pair: the private key never leaves the device (it is stored in a secure enclave or equivalent hardware module), while the public key is registered with the service. During login, the service sends a challenge, the device signs it with the private key, and the service verifies the signature with the public key it already has.</p><p>This design makes passkeys <strong>phishing-resistant by construction</strong>, not just by policy. There is no shared secret to type, copy, or intercept — a fake login page cannot capture a passkey the way it can capture a password or a one-time code, because<strong> the private key simply never leaves the trusted device</strong>. Passkeys are also bound to the origin they were created for, so even if a user is redirected to a lookalike domain, the browser will not offer a matching credential.</p><p>For AI-first systems, this matters beyond convenience. A strong, non-phishable human authentication step is the anchor of the entire trust chain: if the initial login can be bypassed or spoofed, every downstream layer — delegation, scoped tokens, agent identity — inherits that weakness.</p><p>Passkeys give the system a solid starting point: a strongly authenticated human identity with phishing-resistant authentication, which is exactly the precondition OAuth 2.1 needs in order to delegate access safely to an agent.</p><h3>OAuth 2.1 as the delegation layer between human and agent</h3><p>Once the human is authenticated, the next step is <strong>delegation</strong>.</p><p>OAuth is the mechanism that lets a user grant a third-party application limited access to their resources without sharing credentials. In an AI-first system, that third party is often an agent. The point is not to give the agent the user’s password or a full session, but to issue a scoped, temporary, and revocable token that represents only the permissions needed for a specific task.</p><p><strong>OAuth 2.1 </strong>tightens this model by turning the security best practices of OAuth 2.0 into the modern baseline. It requires PKCE for authorization code flows, enforces exact redirect URI matching, and removes weaker grant types such as Implicit and Resource Owner Password Credentials. The result is a delegation flow that is much harder to intercept, replay, or overextend.</p><p>PKCE matters here because it binds the authorization request to the token exchange: even if an authorization code is intercepted, it cannot be redeemed without the original code verifier. That makes it a natural fit for agentic systems, where the risk is not just unauthorized login, but unauthorized escalation during delegation.</p><p>In practice, the flow should look like this:</p><ul><li>The user authenticates with a strong method such as a passkey.</li><li>The user explicitly grants access to the agent.</li><li>The agent receives only the minimum required scope.</li><li>The token expires quickly and can be revoked.</li><li>Every action is attributable to both the agent and the human it represents.</li></ul><p>This separation matters because an agent is not the same thing as a browser session or a backend service — it is a delegated actor. If you blur that boundary, over-permissioning becomes the default.</p><h3>Zero Trust for AI-first applications</h3><p>Once agents become active actors, Zero Trust stops being a slogan and becomes a design requirement.</p><p><strong>Zero Trust </strong>means you do not assume trust based on network location, application boundary, or previous authentication alone. You <strong>verify continuously</strong>. For AI-first applications, that principle needs to be applied across identity, authorization, runtime policy, and observability.</p><p>A practical Zero Trust model for AI-first systems should include:</p><ul><li>strong human authentication with phishing-resistant methods</li><li>explicit agent delegation instead of credential sharing</li><li>least-privilege scopes for every task</li><li>short-lived tokens and frequent renewal logic</li><li>runtime policy checks for sensitive actions</li><li>full audit logging for identity, actions, and context</li><li>step-up verification for high-risk operations</li></ul><p>The main idea is that <strong>trust should be continuously reconstructed, not assumed</strong>. A user may be authenticated once, but an agent’s access still needs to be checked at the moment of every meaningful action.</p><p>This is especially important because AI agents can operate faster than humans can intervene. If a harmful action is allowed to go through once, it can cascade very quickly.</p><blockquote><em>Zero Trust adds friction where it matters most: at the </em><strong><em>point of privilege</em></strong><em>, not just at login.</em></blockquote><h3>Step-up authentication for critical actions</h3><p>Not every action deserves the same level of trust.</p><p>An AI agent might be allowed to draft a report, summarize a dataset, or prepare a deployment plan. But the same agent should not be able to delete production data, change role assignments, rotate secrets, or approve financial transactions without an extra layer of verification.</p><p>That is where step-up authentication comes in.</p><p><strong>Step-up auth</strong> means that a user or agent can operate normally for low-risk actions, but must pass an additional check before high-risk operations. In a human-centric system, that may mean re-entering a passkey prompt, confirming on a trusted device, or requiring secondary approval. In an agentic system, it may mean pausing the workflow until the human explicitly confirms the action.</p><p>A good design principle is to define a “blast radius” (how much damage a single action could cause if it goes wrong) for every agent. The more destructive the action, the more friction you should require.</p><blockquote><strong><em>The system should never let a generic delegated token become a free pass to do irreversible things.</em></strong></blockquote><p>The real-world incidents around deleted databases highlight exactly why this matters. In those cases, destructive operations happened because the agent had too much authority or too little friction at the decision point.</p><p>Step-up authentication is one of the most effective ways to prevent a routine workflow from turning into an outage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUgoiVNy68kNIYD4FirAzA.png" /><figcaption>Step-up Authentication</figcaption></figure><h3>Anti-patterns to avoid</h3><p>There are a few patterns that should be avoided entirely in AI-first systems.</p><ol><li><strong>Letting agents use the user’s password<br></strong>This is the most obvious mistake, and still one of the most dangerous. Agents should never receive or handle primary user credentials.</li><li><strong>Reusing the human session as if it were the agent<br></strong>A delegated agent should not silently inherit the full power of the user session. That destroys accountability and makes revocation nearly impossible.</li><li><strong>Using long-lived tokens with broad permissions</strong><em><br></em>If a token lives too long and can do too much, it eventually becomes an incident waiting to happen.</li><li><strong>Treating agent actions as background noise</strong><em><br></em>Every meaningful agent action should be attributable. Otherwise incident response and forensic analysis become guesswork.</li><li><strong>Skipping human confirmation for destructive operations</strong><em><br></em>If the action is irreversible, the user should know about it. And ideally, they should approve it explicitly.</li><li><strong>Ignoring context and runtime policy</strong><em><br></em>Authentication alone does not guarantee safe behavior. You also need device context, request context, policy enforcement, and observability.</li></ol><p>These anti-patterns are not theoretical. The public incidents around AI agents deleting production systems and backup data are exactly what happens when systems trust agents too broadly and too early.</p><h3>The Anatomy of an AI-First Application</h3><p>An AI-first application is not just a model wrapped in a UI. In production, it is a stack of layers that work together: identity, orchestration, context, tools, execution, security, observability, and governance. If one of these layers is missing, the system may still work in a demo — but it will not be reliable, auditable, or safe enough for real-world use.</p><p>You can think of it like this:</p><ul><li><strong>User &amp; Identity Layer</strong><em>: </em>this is where the human is authenticated and where the agent is identified. In practice, this is where <strong>passkeys </strong>fit best for the human login.</li><li><strong>Delegation Layer</strong><em>: </em>this layer grants scoped access to the agent. This is where <strong>OAuth 2.1</strong> comes into play.</li><li><strong>Orchestration Layer</strong>: this layer coordinates the flow of tasks, decisions, retries, and branching logic. It is especially relevant when multiple tools or sub-agents are involved.</li><li><strong>Context Layer</strong>: this layer provides the data, state, and memory the agent needs to work properly. A good context layer gives the agent enough information to be useful, but not so much that sensitive data is exposed unnecessarily.</li><li><strong>Tool &amp; Integration Layer: </strong>this layer connects the agent to external APIs, databases, SaaS tools, or internal systems. This is one of the most dangerous layers, because this is where actions become real.</li><li><strong>Execution Layer</strong>: this is where actions are actually carried out in a controlled environment. If something goes wrong here, the damage can quickly become operational.</li><li><strong>Security Layer: </strong>this layer enforces policy, boundaries, and trust rules across the whole stack. This is where <strong>Zero Trust principles</strong> belong.</li><li><strong>Observability Layer</strong>: this layer logs traces, decisions, errors, and outcomes. Without observability, debugging and auditing become extremely difficult.</li><li><strong>Governance Layer: </strong>this layer handles compliance, approvals, ownership, and accountability. This becomes crucial once agents start acting in production environments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*hai3VgfHYLwC-voQjFBBPg.png" /><figcaption>Anatomy of AI-First Application</figcaption></figure><h3>A practical implementation on AWS</h3><p>The concepts described so far are not just theoretical — AWS already provides building blocks that map directly onto this model.</p><p><strong>Human authentication with passkeys</strong> can be implemented through <strong><em>Amazon Cognito’s passwordless authentication</em></strong>, which supports FIDO2-based passkeys alongside email and SMS one-time codes. This gives the human login step the phishing-resistant properties described earlier, using the same public-key cryptography model, without building custom WebAuthn logic from scratch.</p><p><strong>Agent identity</strong> can be handled through <strong><em>Amazon Bedrock AgentCore Identity</em></strong>, a service purpose-built to manage agent identities and credentials. It acts as a <strong>centralized directory for agent and workload identities</strong> — a single source of truth, separate from human user identities. What makes it particularly relevant here is that it natively supports OAuth 2.0 flows, including both the <em>client credentials grant</em> (two-legged, for agents acting autonomously) and the <em>authorization code grant</em> (three-legged, for agents acting on behalf of a user) — the same delegation model this article builds around. Credentials, OAuth tokens, and API keys are held in an encrypted token vault, and the AgentCore SDK exposes declarative annotations that automatically retrieve and inject the right credential at runtime, so agents never need to handle raw secrets directly in code.</p><p><strong>Scoped, temporary delegation</strong> maps naturally onto<strong><em> IAM roles combined with AWS STS (AssumeRole)</em></strong>: instead of sharing long-lived credentials, an agent can assume a role with a narrowly defined policy and a short session duration, producing exactly the kind of scoped, expiring, revocable token this article argues for.</p><p><strong>Attribution and auditability</strong> are covered by<strong><em> AWS CloudTrail</em></strong>, which logs every API call together with the identity that made it, and by AgentCore Identity’s own access controls, which preserve an audit trail of which agent acted on behalf of which user — allowing teams to trace an action back to both the agent that executed it and the human identity it was delegated from.</p><p>Together, these services do not form a single pre-packaged product — they are complementary building blocks that need to be architected together. But they show that the principles outlined in this article are not aspirational: the underlying primitives already exist on AWS today, and are recent enough to reflect the current direction of the platform (Cognito passwordless launched in November 2024; AgentCore Identity is part of AWS’s more recent agentic-AI toolset, with native OAuth 2.0 support built in)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*6A9VMffkyn-eJVDR0ZziAg.png" /><figcaption>AWS Services</figcaption></figure><h3>Conclusion: identity, delegation, and verification must be separate, but connected</h3><p>The rise of AI agents changes the entire security conversation. Authentication is no longer just about proving that a human is present. It is about building a trust chain that can survive delegation, automation, and partial autonomy.</p><p>The right model is not one big login event. It is a sequence of connected layers:</p><ul><li>the human authenticates with a phishing-resistant method such as passkeys</li><li>the human delegates limited authority through OAuth 2.1</li><li>the agent operates under its own identity</li><li>the system verifies context continuously under Zero Trust principles</li><li>high-risk actions trigger step-up authentication</li><li>every action is logged, attributable, and revocable</li></ul><p>That separation is the point. Identity, delegation, and verification must remain distinct, because each solves a different problem. But they must also work together, because AI-first systems blur the line between user intent and machine action.</p><h4>In the agentic era, security is no longer just about keeping attackers out. It is about making sure that the systems we build never confuse permission with trust.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7937e14dd762" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-reply-it-datatech/ai-agents-need-identities-too-passkeys-oauth-2-1-and-zero-trust-for-ai-first-applications-7937e14dd762">AI Agents Need Identities Too: Passkeys, OAuth 2.1, and Zero Trust for AI-First Applications</a> was originally published in <a href="https://medium.com/data-reply-it-datatech">Data Reply IT | DataTech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time series with MongoDB]]></title>
            <link>https://medium.com/data-reply-it-datatech/time-series-with-mongodb-dd60f8d6acd6?source=rss-8ecce4f15a4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd60f8d6acd6</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[time-series-collections]]></category>
            <dc:creator><![CDATA[Paoletti Alessia]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 15:19:22 GMT</pubDate>
            <atom:updated>2023-10-05T15:19:22.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zS7BHz0BDqjuON-gR2Tfw.png" /><figcaption>Image from <a href="https://www.percona.com/blog/mongodb-5-0-time-series-collections/">https://www.percona.com/blog/mongodb-5-0-time-series-collections/</a></figcaption></figure><p>Time series data is everywhere, but storing and querying it can be challenging. MongoDB added native support for time series data making it even easier, faster, and cheaper to work with time series data.</p><p>In this article, after a brief introduction on what a time series is, we will introduce <strong>Time Serie Collections</strong> provided by MongoDB from version 5.0.</p><h3>What is a time series?</h3><p>A time series represents a series of observations of well-defined data items obtained through repeated measurements over time. Each entry is preceded and followed by another and has a <strong>timestamp </strong>that determines the order of the data.</p><p>Nowadays times series are everywhere:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVp97SEUyYzmPf03rH2toQ.png" /></figure><p>Time series are mostly used to learn what happened, when happened and why happened in order to try to predict what, where and when it will be happen in the future.</p><p>Time series data is generally composed of <em>three components</em>:</p><ol><li><em>Time </em>when the data point was recorded</li><li><em>Metadata </em>(also know as source), which is a label or tag that uniquely identifies a series and rarely changes</li><li><em>Measurements </em>(also know as metrics or values), which are the data points tracked at increments in time (seconds, minutes, hours, days, months, etc.) Generally these are key-value pairs that change over time.</li></ol><p>For example in a weather data scenario, the metric could be the temperature while the metadata could be the sensor identifier and the location.</p><p>Time series data is often ingested in massive volumes and requires a <strong>purpose-built-database</strong> that can offer scalability and usability. Scalability is needed because time series data grows very quickly; usability means that you may benefit from built-in functions and features to make data analysis tasks easier.</p><h3>MongoDB Time Serie Collections</h3><p>MongoDB is a document database used to build highly available and scalable applications. It uses a JSON-like format to store documents, making easy for developers to store structured or unstructured data.</p><p>From version 5.0 MongoDB offers a specific type of collection to efficiently store time series, the so called <a href="https://www.mongodb.com/docs/manual/core/timeseries-collections/"><strong>Time Series Collections</strong></a>.</p><p>In this type of collections, writes are organized so that data from the same source is stored alongside other data points from a similar point in time. <br>Time series collections use an underlying columnar storage format and store data in time-order with an automatically created clustered index.</p><p>A<em> columnar storage format</em> stores all values of a column as a single record. That means all columns for the dataset are stored in a contiguous row; hence, a row in a columnar storage represents all values for that column.</p><p>The benefits of columnar storage are:</p><ul><li>reduced complexity for working with time series data</li><li>improved query efficiency</li><li>reduced disk usage</li><li>reduced I/O for read operations</li></ul><p>MongoDB treats time series collections as <em>writable non-materialized views</em> backed by an internal collection. When you insert data, the internal collection automatically organizes time series data into an optimized storage format. When you query time series collections, you operate on one document per measurement. Queries on time series collections take advantage of the optimized internal storage format and return results faster.</p><p>When you create a time series collection, MongoDB automatically creates an internal <em>clustered index</em><strong> </strong>on the time field. The internal index provides several performance benefits including improved query efficiency and reduced disk usage. To learn more about the performance benefits of clustered indexes, see <a href="https://www.mongodb.com/docs/manual/core/clustered-collections/#std-label-clustered-collections">Clustered Collections.</a></p><p>Time series collections works as normal collections, you can insert, modify, delete and query your data as you normally do.</p><h4>Create, populate and query time series collections</h4><p>To <strong>create </strong>a time series collection you can use <em>db.createCollection()</em> command and specify the following time series related parameters:</p><ul><li><em>timeField</em>, the name of the field that contains the date in each time series document.</li><li><em>metaField </em>(optional), the name of the field that contains metadata in each time series document.</li><li><em>granularity </em>(optional), can be “seconds”, “minutes”, “hours”. By default is set to “seconds” for high-frequency ingestion.</li></ul><pre># Create &#39;weather&#39; collection <br>db.createCollection(<br>    &quot;weather&quot;,<br>    {<br>       timeseries: {<br>          timeField: &quot;timestamp&quot;,<br>          metaField: &quot;metadata&quot;,<br>          granularity: &quot;hours&quot;<br>       }<br>    }<br>)</pre><p>Once you have created the collection you can <strong>populate </strong>it. Each measurement inserted should be a single measurement, either as individual documents or batches of documents with one measure per document. MongoDB optimizes the data, as it stores data ordered by time (as opposed to normal collections where data are stored in “natural order”, that usually coincide with the inserting order).</p><pre># Insert many documents at once in the collection <br>db.weather.insertMany( [<br>   {<br>      &quot;metadata&quot;: { &quot;sensorId&quot;: 5578, &quot;type&quot;: &quot;temperature&quot; },<br>      &quot;timestamp&quot;: ISODate(&quot;2021-05-18T00:00:00.000Z&quot;),<br>      &quot;temp&quot;: 12<br>   },<br>   {<br>      &quot;metadata&quot;: { &quot;sensorId&quot;: 5578, &quot;type&quot;: &quot;temperature&quot; },<br>      &quot;timestamp&quot;: ISODate(&quot;2021-05-18T04:00:00.000Z&quot;),<br>      &quot;temp&quot;: 11<br>   },<br>   {<br>      &quot;metadata&quot;: { &quot;sensorId&quot;: 5578, &quot;type&quot;: &quot;temperature&quot; },<br>      &quot;timestamp&quot;: ISODate(&quot;2021-05-18T08:00:00.000Z&quot;),<br>      &quot;temp&quot;: 11<br>   },<br>   {<br>      &quot;metadata&quot;: { &quot;sensorId&quot;: 5578, &quot;type&quot;: &quot;temperature&quot; },<br>      &quot;timestamp&quot;: ISODate(&quot;2021-05-18T12:00:00.000Z&quot;),<br>      &quot;temp&quot;: 12<br>   }<br>] )</pre><p>On the <a href="https://www.mongodb.com/docs/manual/core/timeseries/timeseries-best-practices/">documentation</a> you can find some best practice useful when you need to create a time series collection.</p><p>Once data are in the collection you can easily <strong>query </strong>them in many different ways. <br>You can use <em>db.collection.findOne() </em>or <em>db.collection.findMany()</em> to retrieve one or more documents according to the given input filters. You can retrieve a specific measurement or multiple observations in a specific range of time.</p><pre># Find a specific document using its timestamp <br>db.weather.findOne({<br>   &quot;timestamp&quot;: ISODate(&quot;2021-05-18T00:00:00.000Z&quot;)<br>})</pre><p>As in any other MongoDB collections you can perform <strong>aggregation pipeline</strong>. Aggregation pipelines process multiple documents and return computed results. Thanks to aggregation you can group multiple documents together; perform operations on the grouped data to return a single result; analyze data changes over time.</p><pre># Aggregate pipeline to compute the average daily temperature<br>db.weather.aggregate( [<br>   {<br>      # 1. Split timestamp to date component (year, month, day) <br>      $project: {<br>         date: {<br>            $dateToParts: { date: &quot;$timestamp&quot; }<br>         },<br>         temp: 1<br>      }<br>   },<br>   {<br>      # 2. Group data according to the date <br>      $group: {<br>         _id: {<br>            date: {<br>               year: &quot;$date.year&quot;,<br>               month: &quot;$date.month&quot;,<br>               day: &quot;$date.day&quot;<br>            }<br>         },<br>        # 3. Compute average temperature using &quot;temp&quot; field<br>         avgTmp: { $avg: &quot;$temp&quot; }<br>      }<br>   }<br>] )</pre><p>To improve query performance <strong>secondary indexes</strong> on the <em>metaField</em> and/or the <em>timeField </em>can be added<em>.</em></p><h4>Automatic delete or archiving documents</h4><p>After a certain time period time series data might not be so relevant and you might want to delete or archive old data to keep the collections as small as possible, improving performance and reducing costs.</p><p>If you would like to remove data after a certain time has passed you can use the <strong><em>expireAfterSeconds </em></strong>option that enable the automatic deletion of documents by specifying the number of seconds after which documents expire. This parameter can be set or modified at any point during or after collection creation, so if the requirement change, you can easily modify or update the Time To Live (TTL) for your date.</p><pre># Create &#39;weather&#39; collection with TTL option <br>db.createCollection(<br>    &quot;weather&quot;,<br>    {<br>       timeseries: {<br>          timeField: &quot;timestamp&quot;,<br>          metaField: &quot;metadata&quot;,<br>          granularity: &quot;hours&quot;<br>       },<br>       expireAfterSeconds: 86400 # TTL option <br>    }<br>)<br><br># or set/modify TTL option after collection&#39;s creation<br>db.runCommand({<br>   collMod: &quot;weather&quot;,<br>   expireAfterSeconds: 86400 # TTL option<br>})</pre><p>Another option for handling old data is to tier it into operational and online archive storage. Using<em> </em><strong><em>Atlas Online Archive</em> </strong>you can automatically archive data from your Atlas cluster to a MongoDB managed Data Lake. For details information see the official MongoDB documentation on <a href="https://docs.atlas.mongodb.com/online-archive/configure-online-archive/?_ga=2.212336276.1610748035.1687796189-718065813.1650984125">how configuring online archives</a>.</p><h4>Deal with missing data</h4><p>Time series data frequently exhibit gaps for a number of reasons, including measurement failures, formatting problems, human errors or a lack of information to record. On the other hand, time series data must be continuous to perform analytics and guarantee accurate outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgi6eg9A_alGSw14Cmx4Hw.png" /><figcaption>MongoDB time series interpolation</figcaption></figure><p>From version 5.3 MongoDB introduces <strong>gap filling</strong>, to make easier to handle missing data and to allow to bring valuable insight to light. Gap filling is possible thanks to$densify and $fill commands.</p><p>The $densify command creates new documents to eliminate the gaps in the time or numeric domain at the required granularity level.</p><p>The $fill command provides the actual values or data for the new entries. Missing data points can be populated with a fixed values or with a value based on the surrounding documents using linear interpolation or using the value of last or next observation.</p><p>Given a collection with the following two documents, representing the temperature of a given sensor at 8AM and 10AM of 18th of May:</p><pre>[<br>     {<br>      &quot;metadata&quot;: { &quot;sensorId&quot;: 5578, &quot;type&quot;: &quot;temperature&quot; },<br>      &quot;timestamp&quot;: ISODate(&quot;2021-05-18T08:00:00.000Z&quot;),<br>      &quot;temp&quot;: 10<br>   },<br>   {<br>      &quot;metadata&quot;: { &quot;sensorId&quot;: 5578, &quot;type&quot;: &quot;temperature&quot; },<br>      &quot;timestamp&quot;: ISODate(&quot;2021-05-18T10:00:00.000Z&quot;),<br>      &quot;temp&quot;: 15<br>   }<br>]</pre><p>This function produces an hourly view of the temperature. When temperature data is missing it should be interpolated linearly:</p><pre>[<br>  { $densify: {<br>      field: &quot;timestamp&quot;,<br>      partitionByFields: [&quot;metadata.sensorId&quot;],<br>      range: {<br>        step: 1,<br>        unit: &quot;hour&quot;,<br>        bounds: &quot;partition&quot;<br>      }<br>  } },<br>  { $fill: {<br>    partitionByFields: [&quot;metadata.sensorId&quot;],<br>    sortBy: {&quot;timestamp&quot;: 1},<br>    output: {<br>      temp: {method: &quot;linear&quot;}<br>    }<br>  } }<br>]</pre><p>In this way the following document is created at 9AM with a value of 12.5 for the field temperature:</p><pre>{<br>    &quot;metadata&quot;: { &quot;sensorId&quot;: 5578, &quot;type&quot;: &quot;temperature&quot; },<br>    &quot;timestamp&quot;: ISODate(&quot;2021-05-18T09:00:00.000Z&quot;),<br>    &quot;temp&quot;: 12.5<br> }</pre><h4>Time series collections limitations</h4><p>Time series collection have some limitations:</p><ul><li>some feature like Atlas Search, GraphQL API, database triggers are not supported;</li><li>you cannot use <a href="https://www.mongodb.com/docs/manual/reference/operator/aggregation/out/#mongodb-pipeline-pipe.-out">$out</a> or <a href="https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge/#mongodb-pipeline-pipe.-merge">$merge</a> aggregation pipeline stages to add data from another collection to a time series collection;</li><li>you can only set the collection type when you create a collection: an existing collection cannot become a time series collection and, in the same way, a time series collection cannot be converted into a different collection type;</li><li>you cannot write to time series collections in <a href="https://www.mongodb.com/docs/manual/core/transactions/#std-label-transactions">transactions</a>;</li><li>time series collections are <em>writable non-materialized views</em>. Limitations for views apply to time series collections.</li></ul><p>At the following <a href="https://www.mongodb.com/docs/manual/core/timeseries/timeseries-limitations/#std-label-manual-timeseries-collection-limitations">link </a>all time series limitations are reported in details.</p><h3>Code example with PyMongo</h3><p>MongoDB offers <strong>drivers </strong>for all major programming languages, so you don’t have to waste time configuring a database. Check the documentation to discover all <a href="https://www.mongodb.com/docs/drivers/">supported drivers</a>.</p><p>In the following example we will use Python as programming language and <a href="https://www.mongodb.com/docs/drivers/pymongo/">PyMongo</a> as MongoDB driver. <br>MongoDB Community Edition can be installed following this <a href="https://www.mongodb.com/docs/manual/administration/install-community/">guide</a>. Make sure to install version 5.3 or later in order to use time series collection and all related functions.</p><p>In our example we will consider daily weather measurement in the city of Bologna for the month of July. Each measurement is made up of day, temperature, millimeters of rain, percentage of humidity. Data is uncompleted: temperature, rain and/or humidity data was not registered for some days. <br>Here an example of the data for the first five days and the documents that will be inserted in the MongoDB time series collection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*bx6zzQaBfdH18qEMKFW66A.png" /></figure><pre>import pymongo<br>import pandas as pd<br> <br># Connect to the database<br>client = pymongo.MongoClient(&#39;mongodb://localhost:27017/&#39;)<br><br># Get database &#39;italyWeather&#39; (create if does not exist)<br>db = client.italyWeather<br><br># Create time series collection<br>collection_name = &#39;bolognaWeather&#39;<br>db.create_collection(<br>    collection_name,<br>    timeseries= {<br>            &quot;timeField&quot;: &quot;timestamp&quot;,<br>            &quot;metaField&quot;: &quot;metadata&quot;,<br>            &quot;granularity&quot;: &quot;hours&quot;  # seconds, minutes or hours<br>            }<br>)<br><br># Select the collection to use<br>collection = db[&#39;bolognaWeather&#39;]</pre><p>If the collection “<em>bolognaWeather</em>” already exists, the command <em>db.create_collection </em>will throw an error.</p><pre># Insert the list of observation into the collection<br>collection.insert_many([<br>{&#39;timestamp&#39;: Timestamp(&#39;2023-07-01 00:00:00&#39;), &#39;metadata&#39;: {&#39;sensor&#39;: &#39;1234&#39;, &#39;city&#39;: &#39;Bologna&#39;}, &#39;temp&#39;: 40.0, &#39;humidity&#39;: 58.0},<br>{&#39;timestamp&#39;: Timestamp(&#39;2023-07-02 00:00:00&#39;), &#39;metadata&#39;: {&#39;sensor&#39;: &#39;1234&#39;, &#39;city&#39;: &#39;Bologna&#39;}, &#39;temp&#39;: 38.0, &#39;humidity&#39;: 80.0},<br>{&#39;timestamp&#39;: Timestamp(&#39;2023-07-03 00:00:00&#39;), &#39;metadata&#39;: {&#39;sensor&#39;: &#39;1234&#39;, &#39;city&#39;: &#39;Bologna&#39;}, &#39;rain&#39;: 200.0}<br> # ... all the remaining days.... <br>])</pre><p>Due to missing data we can perform $fill command to fill them. This command does not update the documents in the database, but return a list of new documents filled with the missing data according to the chosen method.</p><pre># Perform the fill stage chossing the appropriate method for each field: <br># temperature is filled using linear interpolation<br># rain is filled with constant = 0 (ideally, no data means no rain) <br># humidity is filled with the value of the backward observation<br><br>collection.aggregate( [<br>   {<br>      &quot;$fill&quot;:<br>         {<br>            # data is sorted according to the timestamp<br>            &quot;sortBy&quot;: { &quot;timestamp&quot;: 1 },<br>            &quot;output&quot;:<br>               {<br>                  &quot;temp&quot;: { &quot;method&quot;: &quot;linear&quot; },<br>                  &quot;rain&quot;: { &quot;value&quot;: 0 },<br>                  &quot;humidity&quot;: { &quot;method&quot;: &quot;locf&quot; }<br>               }<br>         }<br>   }<br>] )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*TrJlpFTLLmlFeqFRD1Jq_Q.png" /></figure><p>Thanks to fill stage we have “complete” data on from which we can extract meaningful highlights.</p><h3>Conclusions</h3><p>Nowadays deal with time series data is very common. Time series collection offered by MongoDB allows you to deal with this type of data in an easy and efficient way, letting you concentrate in gaining all the value of the data.</p><h3>References</h3><p>[1] <a href="https://www.mongodb.com/blog/post/introducing-gap-filling-time-series-data-mongodb-5-3">Introducing Gap Filling for Time Series Data in MongoDB 5.3</a></p><p>[2] <a href="https://www.timescale.com/blog/time-series-data/">All Data Is Time-Series Data (With Examples)</a></p><p>[3] <a href="https://www.mongodb.com/docs/manual/core/timeseries-collections/">MongoDB docs — Time Series</a></p><p>[4] <a href="https://www.mongodb.com/docs/manual/core/timeseries/timeseries-limitations/#std-label-manual-timeseries-collection-limitations">Time Series Collection Limitations</a></p><p>[5] <a href="https://levelup.gitconnected.com/data-storage-and-reporting-understanding-columna-vs-row-storage-formats-8cae46347fa3">Understanding Columnar vs Row Storage Formats for Data Analytics and Reporting</a></p><p>[6] <a href="https://www.mongodb.com/docs/manual/core/timeseries/timeseries-best-practices/#best-practices-for-time-series-collections">Best Practices for Time Series Collections</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd60f8d6acd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-reply-it-datatech/time-series-with-mongodb-dd60f8d6acd6">Time series with MongoDB</a> was originally published in <a href="https://medium.com/data-reply-it-datatech">Data Reply IT | DataTech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>