MongoDB sort()

In MongoDB, the cursor.sort() method specifies the order in which the query returns matching documents.

The sort() method accepts a document that specifies the field to sort, and the sort order. The sort order can be either 1 for ascending or -1 for descending.

You can also specify { $meta: "textScore" } when doing $text searches, in order to sort by the computed textScore metadata in descending order.

Continue reading

5 Ways to Get the Hour from a Date in MongoDB

MongoDB provides a good range of aggregation pipeline operators for working with dates, including operators that extract certain parts of dates, such as the year, month, day, hours, minutes, etc.

There are also a couple of MongoDB methods that enable you to iterate through a cursor, and apply a JavaScript function. You can therefore use JavaScript to extract date values and date parts, etc from a field as required.

This article presents 5 ways to return the hour portion from a Date object in MongoDB.

Continue reading

8 Ways to Get the Day from a Date in MongoDB

When extracting the day from a date, the exact option we use will depend on how we want the day to be represented.

For example, do we want the day of the week, the day of the month, or the day of the year? Or perhaps we want it in ISO 8601 format? The return value will usually be different depending on which one we choose.

This article explores those options, and therefore presents 8 ways to return the day portion from a date in MongoDB.

Continue reading

5 Ways to Get the Month from a Date in MongoDB

MongoDB provides a number of aggregation pipeline operators for working with dates, including operators that extract certain parts of dates, such as the year, month, day, etc.

There are also a couple of MongoDB methods that enable you to iterate through a cursor, and apply a JavaScript function. You can therefore use JavaScript to extract date values and date parts, etc from a field as required.

This article presents 5 ways to return the month portion from a date in MongoDB.

Continue reading