Blend field and JavaScript functions while retrieving data from MongoDB

Take a look at this information:

{
"creation_date" : ISODate("2015-02-10T03:00:00.000Z"),
"days_of_validity": 10
}

I need to find all documents where

"creation_date" is less than today - "days_of_validity"

This is what I have come up with so far:

docs.find({"creation_date": 
{$lt: new Date().setDate(new Date().getDate() - days_of_validity)}})

However, it seems like I can't mix JavaScript functions with MongoDB fields.

Do you have any suggestions on how to resolve this issue?

Answer №1

After further calculations, I have come up with some results that may be of assistance to you.

    db.collectionName.aggregate({
    "$project": {
    "creationTimestamp": {
        "$subtract": [{
            "$divide": [{
                "$subtract": ["$creation_date", new Date("1970-01-01")]
            }, 1]
        }, {
            "$mod": [{
                "$divide": [{
                    "$subtract": ["$creation_date", new Date("1970-01-01")]
                }, 1]
            }, 1]
        }]
    },
    "days_of_validity": "$days_of_validity",
    "todayTimeStamp": {
        "$subtract": [new Date().getTime(), 0]
    },
    "creation_date": "$creation_date"
    }
}, {
    "$project": {
    "dayDifference": {
        "$multiply": ["$days_of_validity", 24, 60, 60, 1000]
    },
    "todayTimeStamp": "$todayTimeStamp",
    "creationTimestamp": "$creationTimestamp",
    "days_of_validity": "$days_of_validity",
    "creation_date": "$creation_date"

    }
}, {
    "$project": {
    "todayAndDaysDifference": {
        "$subtract": ["$todayTimeStamp", "$dayDifference"]
    },
    "creationTimestamp": "$creationTimestamp",
    "days_of_validity": "$days_of_validity",
    "creation_date": "$creation_date"
    }
}, {
    "$project": {
    "finalDifference": {
        "$subtract": ["$creationTimestamp", "$todayAndDaysDifference"]
    },
    "days_of_validity": "$days_of_validity",
    "creation_date": "$creation_date"
    }
}, {
    "$match": {
    "finalDifference": {
        "$lt": 0
    }
    }
}, {
    "$project": {
    "days_of_validity": "$days_of_validity",
    "creation_date": "$creation_date"
    }
})

Answer №2

You are facing another challenge here. The issue is that you are attempting to compare one field with another: the variable days_of_validity is not a valid variable in this context. You will need to perform an aggregation operation instead. Consider using the following code snippet:

db.post.aggregate([
    {"$project":{
        "creation_date":1,
        "earliest":{"$subtract":
            [ISODate(), {"$multiply":["$days_of_validity", 1000*3600*24]}]}}},
    {"$project": {"delta": {"$subtract":["$creation_date", "$earliest"]}}},
    {"$match":{"delta": {"$lt": 0}}}])

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

Retrieve the package.json file for a specific package by making an HTTP request to public repositories

I’ve been searching online but haven’t found a satisfying answer to my question yet. My main objective is to generate a dependency tree for a particular npmjs library of a specific version, like retrieving the dependency tree for the angular library v ...

Working with Node.js and JavaScript's Date object to retrieve the time prior to a certain number of hours

I am currently working on a script in node.js that is able to locate all files within a specific directory and retrieves their modified time: fs.stat(path, function(err, states){ console.log(states.mtime) }) After running the script, it ...

Do I have to cram all the content onto a single page just to use a scroll effect?

I'm currently facing a dilemma as I work on building my portfolio. My goal is to primarily use html5 and css3, along with a bit of js, jquery, and other tools if necessary. Although I am not an expert in web development, I wanted to push myself to cre ...

Troubleshooting a mysterious anomaly with a jQuery UI button

Would like to achieve something similar to this: http://jqueryui.com/demos/button/#icons When trying to replicate it, http://jsfiddle.net/p5PzU/1/ Why is the height so small? I expected a square shape but am getting a rectangle instead. What could be c ...

Dynamically update a directive array in Vue.js based on real-time changes

In my Vue project, I have an array defined in the data() method that is populated through a custom directive in its bind hook. Here's the code snippet: import Vue from 'vue' export default { el: '#showingFilters', name: "Filte ...

Unable to establish connection with remote database server on Hostinger platform

I've been encountering this persistent error that I can't seem to resolve. I developed my project locally, utilizing a local database. Upon completion, I attempted to manually migrate my database to my hosting provider since it's relatively ...

Retrieve worldwide data for the entire application in Next.js during the first page load

Within my Next.js application, I am implementing search filters that consist of checkboxes. To display these checkboxes, I need to retrieve all possible options from the API. Since these filters are utilized on multiple pages, it is important to fetch the ...

convert the datatype of JSON values in JavaScript

I am facing an issue with my JSON object which contains timestamp values in string format. Here is a snippet of the data: var json = [{ "Time": "2017-08-17 16:35:28.000", "Value": "3.85" }, { "Time": ...

Express file response problems affecting React front-end communication

I am currently developing a basic questionnaire on a React full stack website that uses React, Express, and SQL. Right now, my main goal is to return an error message from React and have it displayed on the front end. This is the code for my express endp ...

Using AJAX to upload an image and passing multiple parameters

I'm facing an issue when trying to upload an image along with other input text in a form and send it to ajax_php_file.php. Whenever I upload the image, all my input text fields appear empty. Any assistance would be greatly appreciated. Thank you very ...

Tips for efficiently expanding NodeJS while running it through an Apache web server?

Currently, I have Apache Web Server running alongside NodeJS on the same system but on different ports. I am reverse proxying to connect and use them for various purposes. My concern is how to scale this architecture up to accommodate around 10 million u ...

Establishing a global variable in Cypress through a function

My current workflow involves the following steps: 1) Extracting a field value from one page: var myID; cy.get('#MYID'). then(($txt) => { myID= $txt.text(); }) .should('not.equal', null); 2) Mo ...

I am having trouble getting the hoverOffset feature to work with doughnut charts in vue-charts.js

It appears that no matter what I try, the hoverOffset property is not working on my doughnut charts. Here's the component code: <script> import { Doughnut } from 'vue-chartjs' export default { extends: Doughnut, props: { ch ...

Troubleshoot: Node Express experiencing issues reconnecting to ajax

Here is the initial question that needs to be addressed. I am currently developing an API that links a front-end application (built using node, express, and Ajax) with a Python swagger API. The issue I am facing is that although I can successfully send da ...

How can this JSON function correctly?

Hey there! I've been trying really hard to receive a response from PHP and based on that response, perform different actions. However, I seem to be facing some challenges with handling the output from the PHP file. Below is a snippet of my index file: ...

How can I create numerous HTML containers using Javascript?

I've been learning from this tutorial: Instead of just displaying the last database object, I want to display all of them. I have tried outputting the database contents and it's working fine. Now, I just need to adjust the HTML. I attempted to ...

How can I transfer data from a MySQL callback function to a global variable?

I'm still in the learning stages of using nodejs and working on getting more comfortable with it. My goal is to retrieve a user from a database and store it in a variable, but I'm having trouble storing it globally. Though I can see that the conn ...

Managing State in React using Maps

As someone who is new to coding, I am currently facing an issue and seeking help to resolve it. I am using axios to retrieve a JSON file and store it in a state utilizing Redux for form population. I am then utilizing .map() to break down the array and dis ...

Angular JS basic API: Displaying only information that starts with the term 'request'

I've been given the task of developing a straightforward AngularJS API. I have managed to set up the basics for displaying data, but I'm facing an issue where the table only retrieves data from the JSON file if it starts with "request". As a resu ...

extracting both the value and ID attributes from a RadioButtonGroup component in React MaterialUI

I am currently working on extracting the selected value and gameID from a dynamic MaterialUI RadioButtonGroup. Although I have been successful in retrieving the gameID, I am encountering difficulty in obtaining the value: <form onSubmit={this.handl ...