Including an identical field within the parameters of a MongoDB search query

In my mongodb collection testdata, there is a field named insertTime. Our goal is to remove data older than 60 days. Previously, to accomplish this, I would use the logic of finding the deletion date and then comparing it against the updateTime:

var date = new Date();
var daysToDeletion = 60;
var deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));
deletionDate = deletionDate.toISOString()
printjson(insertDate);

db.testdata.find({"insertTime":{ $lt: deletionDate}})

Now, I want to delete records older than each record's alive time. The alive time is calculated as the sum of insertTime and endTime (60 days). Documents older than this alive time minus 60 days should be deleted. Any ideas on how to achieve this in mongodb find command query?

This is what I have come up with so far, but I am not sure if the syntax is correct:

db.testdata.find({"insertTime"+endTime:{ $lt: deletionDate}})

Any insights on how to accomplish this task using the MongoDB find command would be greatly appreciated.

Additional details and goals have been included in the post.

EDIT: Currently using AWS documentDB 4.0.0

Answer №1

Take a look at this $expr for a possible solution:

var date = new Date();
var daysToDeletion = 60;
var deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));

db.testdata.deleteMany({
    $expr: {
        $lt: [{ $add: ["$insertTime", "$endTime"] }, deletionDate]
    }
});

Update: Here's a solution that is compatible with documentdb:

var date = new Date();
var daysToDeletion = 60;
var deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));

db.testdata.find(
    {
        $lt: {
            $add: [
                "$insertTime",
                { $multiply: [daysToDeletion, 24 * 60 * 60 * 1000] }
            ]
        },
        deletionDate
    }
);

Update 2: The previous solution was not functioning correctly.

This one is a bit complex, but it gets the job done

const date = new Date();
const daysToDeletion = 60;
const deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));
const aliveTime = { $add: ["$insertTime", "$endTime"] };

db.testdata.deleteMany({
  $and: [
    { aliveTime: { $lt: deletionDate } },
    { insertTime: { $lt: deletionDate } }
  ]
});

Answer №2

One way to calculate the alive date in MongoDB (v5.0+) is by using the function $dateAdd and then comparing it to $$NOW.

db.collection.find({
  $expr: {
    $lt: [
      {
        "$dateAdd": {
          "startDate": "$insertTime",
          "unit": "day",
          "amount": 60
        }
      },
      "$$NOW"
    ]
  }
})

Check out the Mongo Playground for this code


For MongoDB / AWS DocumentDB (v4.0), you can achieve the same result by adding 60 days worth of milliseconds (5184000000) to the insert time and then comparing it to $$NOW.

db.collection.aggregate([
  {
    "$addFields": {
      flag: {
        $lt: [
          {
            $add: [
              "$insertTime",
              5184000000
            ]
          },
          "$$NOW"
        ]
      }
    }
  },
  {
    "$match": {
      flag: true
    }
  },
  {
    "$unset": "flag"
  }
])

Check out the Mongo Playground for this code

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for resolving issues with mat-autocomplete during scrolling

When I open the mat-autocomplete and scroll down the page, I would like for the mat-autocomplete to stay in place. ...

Determining intersecting date ranges within sub-documents using MongoDB

Consider the following dataset: [{ "name": "First Workshop", "participants": ["5d2eca379b0d361b18d2f3d0", "5d31290c21729014a0bdd0ba"], "schedule": [{ "start": "2019-10-07T12:00:00.000Z", "end": "2019-10-07T14:00:00.000Z" }] ...

Looking to implement client-side JavaScript validation prior to utilizing jQuery AJAX validation

I'm struggling to make sure that my validate(form) function runs "before" my ajax function. I would appreciate any suggestions on how to connect the two and ensure they run in sequence when the form is submitted. Thank you! <script type="text/ ...

Prevent JavaScript from sending a POST request to a specific URL

Currently facing Cross Site Scripting (XSS) vulnerabilities in a web application, I am curious if there are security measures equivalent to Content-Security-Policy: frame-ancestors and X-Frame-Options for JavaScript. My objective is to restrict the abilit ...

Fixed Positioning Div to Stay at the Top while Scrolling

Currently, I have successfully implemented the functionality to stick the div to the top once it scrolls down by 320px. However, I am curious if there is an alternative approach to achieving this effect. Below is the code snippet I am using: jQuery(functi ...

The IE9 confirmation dialog fails to pause for user response, resulting in automatic postback before user input is received

Behind the Scenes btnNext.Attributes.Add("onclick", " return Verification(this,'" + GetLocalResourceObject("message").ToString() + "'); ") .ASPX Page [Within javascript tags] function Verification(source, message) { var dialog = '< ...

Contrasting characteristics of class members in JavaScript versus TypeScript

Typescript, a superset of Javascript, requires that Javascript code must function in Typescript. However, when attempting to create class members in a typescript file using the same approach as Javascript, an error is encountered. CODE :- script.ts (types ...

Generate a collection of LatLng coordinates to represent a worldwide grid

I'm in search of a quick and easy solution, like a simple library or similar tool, that would allow me to call a function like createGlobalGrid(1000) and automatically generate a list of points on a geospatial surface, ensuring that each point is no m ...

What is the best way to achieve a precision of 6 decimal places in JavaScript when working with decimals?

While working on coding to round numbers to six decimal places after performing some arithmetic operations, I encountered a problem. I was iterating through the elements of an array and conducting calculations based on the array contents. To achieve roundi ...

Can a plugin be executed as a test?

I am currently using HTMLhint, however, I would like to have it run as a test rather than just through the command line plugin. Is there a way to achieve this and if so, how can I do it? I have searched online but haven't been able to find a solution ...

Tips for making an ajax call in Angular 6

As a backend developer, I have limited experience with Angular. How can I send an ajax request from Angular to test my API? The request needs to be sent before clearing the localeStorage. Can you provide guidance on how to achieve this? <button (clic ...

Storing JavaScript code in a PHP variable fails to function

I've encountered an issue with my JavaScript code. <script> $(document).ready(function(){ $('.delete').click(function() { alert('passed'); }); }); </script> Everything work ...

What is the best way to have a form open upwards when hovered over or clicked on?

Attempting to create a button in the bottom right corner that will reveal a form when clicked or hovered over. The form should slide open slowly and close after clicking on login, but currently the button is moving down as the form opens. The button also ...

The useParams() function is returning undefined, even though the parameter does exist in the destination URL

I have a complete inventory of items called "Commandes" (PS: the app is in French), displayed in a table with a column for each row that should redirect me to another component showing more details about the selected row. To achieve this, I need to utilize ...

Utilizing Redux-Form to Retrieve Input Values

When a radio button is clicked, I want to display a form using redux-form. I tried following a tutorial that uses checkboxes but couldn't figure out how to implement it with radio buttons. The tutorial link is selectingformvalues. I have 2 radio butt ...

Angular throws an error when trying to parse undefined data outside of an async function

I'm having trouble parsing data retrieved from an http call and passing it to ngOnInit. Can you assist me in finding a solution? My project is built with Angular 4. Here's the async function: async getAsyncData() { this.asyncResult = awai ...

Exploring jQuery AJAX and how to effectively manage various data types

ASP.Net MVC is the framework I am currently using, but this issue can apply to any framework out there. When making an Ajax call to my server, most of the time it returns plain HTML content. However, in case of an error, I want it to return a JSON object ...

Retrieve the designated element from an array of JSON data in SPLUNK

As a newcomer to the world of Splunk, I am facing a challenge with handling JSON data. Here is an example of the JSON data I am working with: "request": { "headers": [ { "name": "x-real-ip", "value": "10.31.68.186" ...

Take action upon window.open

I have a code snippet here that opens a window. Is it possible to make an ajax call when this window is opened? window.open("http://www.google.com"); For instance, can I trigger the following ajax call once the window is open: var signalz = '1&apos ...

Saving data from Material UI forms in TypeScript

Is there an effective method for storing values entered into the text fields on this page? const AddUserPage = () => ( <div> <PermanentDrawerLeft></PermanentDrawerLeft> <div className='main-content'> < ...