Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb find created results by date today

I have this query to get results on month. But I wanted to get the results of today.

var start = new Date(2010, 11, 1);
var end = new Date(2010, 11, 30);

db.posts.find({created_on: {$gte: start, $lt: end}});

What is the best way to do this?

like image 759
Rex Adrivan Avatar asked Mar 29 '15 08:03

Rex Adrivan


People also ask

How does MongoDB match current date?

The current date in the MongoDB query The following two ways return date as a string or as a date object: The Date() will return the current date as a string. The new Date() will return the current date a date object and MongoDB cover the Date object with the ISODate.

What does find () do in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.


1 Answers

Your start date object should hold the current date time hours at 00:00:00.000 (milliseconds precision) and set the hours for today's date to 23:59:59.999:

var start = new Date();
start.setHours(0,0,0,0);

var end = new Date();
end.setHours(23,59,59,999);

Then pass the modified date objects as usual in your MongoDB query operator:

db.posts.find({created_on: {$gte: start, $lt: end}});

If you are using the dayjs date utility library, this can be done by using the startOf() and endOf() methods on dayjs current date object, passing the string 'day' as argument:

const start = dayjs().startOf('day'); // set to 12:00 am today
const end = dayjs().endOf('day'); // set to 23:59 pm today

You can also use $expr as follows:

db.posts.find({
    $expr: {
        $eq: [
            { $dateToString: { format: '%Y-%m-%d', date: '$$NOW' } },
            { $dateToString: { format: '%Y-%m-%d', date: '$created_on' } },
        ],
    },
})
like image 189
chridam Avatar answered Oct 05 '22 13:10

chridam