How to Format the Date in MongoDB

If you have documents that store dates as Date objects, but you want to return them in a different format, you can use the $dateToString aggregate pipeline operator.

For example, you might want a date to be returned in mm/dd/yyyy format instead of the long ISODate() format that includes minutes, seconds, milliseconds, etc

The $dateToString operator converts the Date object to a string, and optionally allows you to specify a format for the resulting output.

Continue reading

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

MongoDB $orderBy

In MongoDB, the $orderBy query modifier sorts the results of a query in ascending or descending order.

$orderBy 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.

$orderBy has been deprecated in the mongo shell since v3.2. Use the cursor.sort() method instead.

Continue reading