cKendrick
cKendrick

Reputation: 207

MongoDB Sort Array

Is it possible to sort my MongoDB array of reviews by the date the review was made? Would I have to do this in my server-side script rather than by using a query operator? If so how would I do that?

{
  "review": [
    {
      "date": "2012-05-04 21:06:58",
      "review": "The Review",
      "name": "The Persons Name",
    },
    {
      "date": "2012-09-04 21:06:58",
      "review": "The Review",
      "name": "The Persons Name",
    },
    {
      "date": "2012-02-04 21:06:58",
      "review": "The Review",
      "name": "The Persons Name",
    }
  ],
  "category": "Category 1",
  "country": "USA",
  "date": "2012-05-04 21:06:58"
}

Upvotes: 2

Views: 1006

Answers (1)

Fad
Fad

Reputation: 9858

Since you put in the tags, I assume that you're working with PHP. You can create your own sorting function for this and have it called by PHP usort() function.

function sort_date($a, $b)
{
    return (strtotime($a['date']) - strtotime($b['date']));
}

usort($reviews_array, 'sort_date');

The above code will sort the reviews by date in ascending order.

Upvotes: 2

Related Questions