1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In fact, I need to compare the timestamp(since 1970) stored in db and the day of today ("YYY-MM-DD"), and I dont know how to make this opération
@user3660934 Timestamps as a number is just a simple matter of convertion. See the additional details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.