Answer the question
In order to leave comments, you need to log in
How to get all values in a certain time interval from mongoDB?
I am making a system that receives data from the server and stores it in MongoDB. The server in the json response gives the UNIX time and the value of the value of interest. I need to save the value and time itself. Further, I need the user to specify the start and end times and get all the values that lie in the specified time interval. Please tell me how to optimally organize data storage in MongoDB, so that later with one query you can get all the values for a time interval
Answer the question
In order to leave comments, you need to log in
In general, there are 2 generally equivalent ways of obtaining results.
The first is to store Unixtime as NumberLong() and work with comparison operators . NumberLong is stored as a 64-bit integer.
The second is to use the Date() type and translate Unixtime into it. Comparison operators will also work with it.
Both options are basically the same, because. the object will be converted to the same 64-bit integer.
The difference will be at the level of communication with the base, in the first case you will have to turn all dates into a number and pass this number to the base, in the second you will pass the Date () object.
I would recommend using Date(), and if you don't have values scheduled at the same time, store it inside the _id field. This way you can save the index.
You can also do this:
1) In Schema:
...
date: {
type: String,
},
...
2) When saving, we write milliseconds there (the result of Date.prototype.getTime())
3) Sample query:
db.collection. find({$and:[{date:{$gte:'1471974357000'}}, {date:{$lt:'1471974537000'}}]}).pretty()
4) If using mongoose for example, it looks like something like this:
findQuery.$and.push({
date: { $gte: `${new Date(year, month, day, hour).getTime()}` },
}) etc.
Upd: To convert unixtime to Date.prototype.getTime format, you just need to multiply it by 1000
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question