Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7015583
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T22:40:17+00:00 2026-05-27T22:40:17+00:00

I am adding entries to a schema every hour in order to track growth

  • 0

I am adding entries to a schema every hour in order to track growth over the course of days while maintaining a current score for the current day. Now I would like to be able to pull the most recent record for each day for the past week. The results would be 6 records at or around midnight for 6 days previous and the 7th being the latest for the current day.

Here is my schema:

var schema = new Schema({
  aid: { type: Number }
, name: { type: String }
, score: { type: Number }
, createdAt: { type: Date, default: Date.now() }
})

Edit

I’ve tried using this static, but it pulls the exact same record 7 times

schema.statics.getLastWeek = function(name, fn) {
  var oneday = 60 * 60 * 24
    , now = Date.now()
    , docs = []

  for (var i = 1; i <= 7; i++) {
    this.where('name', new RegExp(name, 'i'))
    .where('createdAt')
    .gte(now - (i * oneday))
    .desc('createdAt')
    .findOne(function(err,doc){
      docs.push(doc)
    })
  }
}

If I were using SQL I would do a subquery selecting MAXDATE and join it to my main query in order to retrieve the results I want. Anyway to do this here?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T22:40:18+00:00Added an answer on May 27, 2026 at 10:40 pm

    Kristina Chodorow gives a detailed recipe for this exact task in her book MongoDB: The Definitive Guide:

    Suppose we have a site that keeps track of stock prices. Every few
    minutes from 10 a.m. to 4 p.m., it gets the latest price for a stock,
    which it stores in MongoDB. Now, as part of a reporting application,
    we want to find the closing price for the past 30 days. This can be
    easily accomplished using group.

    I’m not familiar with Mongoose, however I’ve tried to adapt her example to your case below. Note I changed the createdAt default property from a value to a function and added an extra field datestamp to your schema:

    var oneday = 24 * 60 * 60;
    
    var schema = new Schema({
      aid: { type: Number }
    , name: { type: String }
    , score: { type: Number }
    
      // default: is a function and called every time; not a one-time value!
    , createdAt: { type: Date, default: Date.now }
    
      // For grouping by day; documents created on same day should have same value
    , datestamp: { type: Number
                 , default: function () { return Math.floor(Date.now() / oneday); }
                 }
    });
    
    
    schema.statics.getLastWeek = function(name, fn) {
        var oneweekago = Date.now() - (7 * oneday);
    
        ret = this.collection.group({
              // Group by this key. One document per unique datestamp is returned.
              key: "datestamp"
              // Seed document for each group in result array.
            , initial: { "createdAt": 0 }
              // Update seed document if more recent document found.
            , reduce: function(doc, prev) {
                  if (doc.createdAt > prev.createdAt) {
                    prev.createdAt = doc.createdAt;
                    prev.score = doc.score;
    
                    // Add other fields, if desired:
                    prev.name = doc.name;
                  }
              // Process only documents created within past seven days
            , condition: { "createdAt" : {"$gt": oneweekago} }
            }});
    
       return ret.retval;
    
       // Note ret, the result of group() has other useful fields like:
       // total "count" of documents,
       // number of unique "keys",
       // and "ok" is false if a problem occurred during group()
    
    );
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i am updating a table in mysql using ADODB i am adding new entries
I am using QT4 and dynamically adding entries to a QMenu. Is it possible
I am building a dynamic form in that the user can keep adding entries
i have a function in Lua that operates on a table, repeatedly adding entries
I have a small database and have been adding entries through a Rails page.
I'm looping through the Session keys and adding entries and their values to a
A buddy of mine needed help adding multiple directories to an SQL database while
Adding more and more configurations to my servlet container ( Embedded Jetty in my
Adding more than one child to a WPF StatusBar results in poor layout with
Adding Exceptional Handling is a good practise, but I have a doubt, In our

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.