user1213904
user1213904

Reputation: 1940

Save time in mongodb

I have tried to save a specific time into my mongodb database with the javascript date object like:

var currenttime = new Date();
currenttime.setHours(14);
currenttime.setMinutes(37);

db.test.insert({time: currenttime});

however I have noticed that not only are the hours and minutes saved, but also the date. I am searching for a way to only save the hours and minutes, but in a way that I can still do less than greater than operations on it. Is there a way to do this?

Upvotes: 0

Views: 6675

Answers (3)

iCPSoni
iCPSoni

Reputation: 136

Basically you can try these two options to save time:

  1. Save time as type: String
const userInput = '05:20';
const hours = userInput.slice(0, 2);
const minutes = userInput.slice(3);
  1. Save date time in type: Date

But in second option you have to create Date object and set hours and minutes:

const date = new Date(dateString);
date.setHours(hours, minutes);

Upvotes: 1

Jason Ching
Jason Ching

Reputation: 2229

You can consider to save number of minutes as an integer field.

For example, 8:30 will be converted as 8 hour * 60 minutes + 30 minutes = 510 minutes. Save 510 as an number in MongoDB.

Upvotes: 3

Salvador Dali
Salvador Dali

Reputation: 222531

MongoDb Date is only 64bits, on the other hand if you will store your time as just 2 32 bit integers (hours and minutes) you will be already using these 64 bits. If you will save them as a 4 letters string, it will be even more.

So you can not gain space advantage. But you will lose advantage of querying your data. It will be harder to find all elements that are bigger than particular time with 2 numbers format and even harder with strings.

So I would save them as dates. If you really need only time - and need to query by this time, you can do the following trick: make all dates the same. For example:

 var a = new Date();   // gives current date and time (note it is UTC datetime)
 a.setYear(2000);
 a.setMonth(0);
 a.setDate(1);
 db.test.insert({time: currenttime});

This way all the elements will have the same date and different time. In such a way you sort them properly. Also if you need to find all the elements where time is smaller than a particular time, you can quickly create a date object with year/month/day (2000/0/1) and query your data properly.

Upvotes: 2

Related Questions