Ronak07
Ronak07

Reputation: 894

How to make query to find past six months date in mongodb

I am stuck in a problem where I want to make query to find past six months date.

I have a scenario in which I want the sum of quantity weekly, which I have achieved but I want to make a query which can find the date from current date to past six month date so how can i achieve it mongodb.

Any help would be appreciated.

db.rxTable.aggregate([
    {
        $addFields: {
            rxDate: {
                $dateFromString: {
                    dateString: "$rxDate"
                }
            },
            quantity: {
                $toInt: "$quantity"
            }
        }
    },
    {
        $group: {
            _id: { $week: '$rxDate' },
            data: {
                $addToSet: "$$ROOT",
            },
            sales: {
                $sum: "$quantity"
            }
        }
    }
])

I have also added my query down below.

For example I have tried this scenario in javascript in console but I want it in mongodb.

Here I am posting my example i tried in console.

var sixMonths = 1.577e+10;

sixMonths
15770000000

Date.now()
1589292791593

var current = Date.now();
undefined

current-sixMonths
1573522803658

Date(current-sixMonths)
"Tue May 12 2020 19:43:45 GMT+0530 (India Standard Time)"

Date(current-sixMonths)
"Tue May 12 2020 19:44:21 GMT+0530 (India Standard Time)"

new Date(current-sixMonths)
Tue Nov 12 2019 07:10:03 GMT+0530 (India Standard Time)

new Date()
Tue May 12 2020 19:55:19 GMT+0530 (India Standard Time)

Upvotes: 2

Views: 2333

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

You can try below query :

db.collection.aggregate([
   /** $$NOW gives you current date */
  {
    $project: { sixMonthOldDate: { $subtract: [ "$$NOW", 15770000000 ] } }
  }
])

Test : mongoplayground

Upvotes: 2

Related Questions