0

my project is based on Hapi.js and Mongoose. I'm stuck in getting the X prices from 24h ago.

I'm getting the latest added record in this way:

        const pricesnow = await Prices.find({
          currency_id: {
            $in:
              currencies[k].id
          },
          createdAt: {
            $gt: new Date().getTime() - 1000 * 60 * 1
          }
        })

So I thought that I can get the x records from 24h ago with this code:

        const prices24h = await Prices.find({
          currency_id: {
            $in:
              currencies[k].id
          },
          createdAt: {
            $gt: new Date().getTime() - 86400000,
            $lt: new Date().getTime() - 86399999
          }
        })

But even there is data in the database, the prices from 24 hours ago doesnt return.

The second code only works if the time span is within an hour.

After that I'm going to subtract prices24h from pricesnow to calculate the 24h percentage.

Thanks in advance for your answers.

Rosina
  • 115
  • 11

2 Answers2

2

You can use limit and sort functions along with find

const pricesnow = await Prices.find({
  currency_id: {
    $in: [], // replace with currency array
  },
  createdAt: { $gt: new Date(Date.now() - 86400000) },
})
  .sort({ createdAt: -1 })
  .limit(10);

vishnu
  • 1,961
  • 2
  • 7
  • 11
  • But if I just do sort, then the data from more than 24h will come. And I need the data from exactly 24h ago – Rosina Jun 08 '20 at 15:37
  • @Rosina The `find` statement should have that condition like `find({{"createdAt":{$gt:new Date(Date.now() - 86400000)})` to get only the last 24 hour record and then you shoud `sort` it – vishnu Jun 08 '20 at 15:48
  • I just tried it and it isn't working. With sort it is returning too much data, and after I tried it without sort just limit, it is returning only the same currency for 30 times. – Rosina Jun 08 '20 at 16:08
  • @Rosina I have updated the answer. Can you please confirm whether you are executing the same – vishnu Jun 08 '20 at 16:25
0

Visit MongoDB: Only fetch documents created in the last 24hrs?

Try this link hope it will help you

db.getCollection("COLLECTION_NAME").find({"createdAt":{$gt:new Date(Date.now() - 24*60*60 * 1000)}})

Thank you

aum trivedi
  • 129
  • 4
  • Hi. thanks, but I don't want **every** record from the last 24h. Only the last **X**. How can I do that? – Rosina Jun 08 '20 at 13:31