mfrachet
mfrachet

Reputation: 8922

Mongodb get information by date (timestamp stored in db)

I need to get all information stored in my (mongo)DB in a collection filtered by a date.

The problem is that I store a timestamp in my BD, and I need to get all information for a day.

Example, if I chose the 2014-01-08, I have to get all the treatment done during this day

Can you help me with the mongo request ?

Thanks for advance

Upvotes: 1

Views: 332

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151072

Query by using a date range with a "range based query", which is a simple treatment of the $gte and $lt operators:

Assuming you actually mean "YYYY-MM-DD" as in "year" "month" "day":

db.collection.find({
    "dateField": { 
        "$gte": new Date("2014-08-01"),
        "$lt": new Date("2014-08-02")
});

So that basically selects all items that fall within that date range being only occurring on "2014-08-01" only. So the range is all values that fall within that range.

If your timestamp is actually a number ( milliseconds since epoch ) then you just extract those values from date objects you create and send those in the query:

db.collection.find({
    "dateField": { 
        "$gte": new Date("2014-08-01").valueOf(),
        "$lt": new Date("2014-08-02").valueOf()
});

The same principle applies for just about any language as the supported DateTime object will have a method to do so.

If you are doing this then you might re-consider your approach. MongoDB uses a BSON Date type, which aside from the "type" identifier, actually stores the timestamp number internally. So there is basically no overhead to BSON dates, and they automatically inflate to DateTime objects with all drivers, as well as being supported by other internal operators.

Upvotes: 1

Related Questions