Fabio B.
Fabio B.

Reputation: 9400

Querying by date, regardless time part

I want to show my blog posts, paginated by creation date. I will have a page for 5 posts written in 2012-10-01, a page for 11 posts written in 2012-10-03 and no page at all for 2012-10-02 (no posts written)

Each post document is stored with a creation date which is a datetime value, here's a mongoose snippet:

var postSchema = new Schema({
    url: String,
    creationDate: {type: Date, default: Date.now},
    contenuto: String,
});

so it will have something like 2012-10-01 18:45:03... know what I mean.

In my code, I will create a

var searchDate = new Date(yy,mm,dd);

How can I use that for querying the posts collection, without considering the "time part" of creationDate?

I'm not sure this would always work:

Post.find({ creationDate:dataRicerca })

Upvotes: 2

Views: 6771

Answers (1)

cirrus
cirrus

Reputation: 5662

As per this post;

How do I resolve a year/month/day date to a more specific date with time data in MongoDB?

you can store the data separately (as well as the full date) in your schema for easier searching. You could also do this;

Post.find({Posted:{$gt: Date("2012-10-01"), $lt:Date("2012-10-02")}})

(updated to use Date() rather than ISODate() for better compatibility)

Upvotes: 6

Related Questions