How to obtain data from mongoose collection according to week month or years? P.S every document is stored or updated as a single document for a day

Viewed 115

I have to show a chart in frontend which takes an array of numbers (7 for a week, 12 for months and 5 for years as shown as shown in the image). Week Month Year In backend I had a document for everyday which stores and updates on daily basis as unique for a day storing total energy delivered. Currently I have timestamps in epoch time but I can change it to anything which fulfils my needs.

I want to write queries for obtaining data based on selection using bPID. Suppose I select week it queries last 7 document for a particular bPID and return it to me so that I can filter it out. Suppose I select months so it returns me 31 collections for Jan and 28 for Feb which I would process it in my backend and get an array of 12 for a month. How to query this so that in the end I end up getting array of 7 documents for a week, 12 for a month, 5 for a year.

My current collection:

const analyticSchema = new Schema(
  {
    bPID: String,           // unique for every document
    todaysTimeStamp: Number,  // epoch time for 12:00 am 
    energyConsumed: Number
  },
  {
    timestamps: true
  }
);
1 Answers

You can get last 7 document for a week, for months you have to query based on this month and get last 365/366 documents. Filter it out based on months. For years you have to get it as mentioned above.

Related