0

consider this mongo collection with following documents and props.

{sku: '3344', frequency: 30, lastProccessedDate: 2021-01-07 15:18:07.576Z},
{sku: '2233', frequency: 30, lastProccessedDate: 2021-02-16 15:18:07.576Z},
{sku: '1122', frequency: 30, lastProccessedDate: 2021-04-13 15:18:07.576Z}

I want to query and get all the documents with (lastProcessedDate + frequency (days)) <= current date.

Essentially in SQL world this is possible to do it, but I can't figure it out to do it in mongo or even if it is possible to do it.

In SQL this would be something like SELECT * FROM table WHERE DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(lastProcessedDate), INTERVAL frequency DAY), '%Y-%m-%d') <= CURDATE()

If it is not possible I know I can store the calculated date in the document and just query based on that but you know I want to know if it is possible to do it.

Thank you all!

1 Answer 1

1

Unfortunately, I can't give you a solution for mongoose. But here is the Mongo query that returns the result you want:

db.getCollection("yourCollection").aggregate([
{
   $project: {
       _id: 1,
       sku: 1,
       frequency: 1,
       lastProccessedDate: 1,
       shiftedDate: {
           $add: [
               "$lastProccessedDate", { $multiply: [ 24 * 60 * 60 * 1000, "$frequency" ] }
           ]
       }
   } 
}, {
    $match: {
        shiftedDate: { $lte: new Date() } 
    }
}, {
    $project: {
        _id: 1,
       sku: 1,
       frequency: 1,
       lastProccessedDate: 1,
    }
}
])

First, we transform documents to new form that contains the same fields plus a new temporary field - a "shifted" date that is defined as lastProccessedDate + frequency (days) (pay attention that we actually add milliseconds, so there's 24 * 60 * 60 * 1000 in the query). Then we select only that documents which shiftedDate is less than (or equals) current timestamp (new Date() returns current timestamp). Finally, we transform the filtered documents to original form, without the temporary field we used to filter the documents previously.

Perhaps there's a better solution to get documents you want, but this one can resolve your problem too.

Sign up to request clarification or add additional context in comments.

1 Comment

Instead of $project you can use $set. Then you save all the xx: 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.