2

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"
}
1
  • sort review array by usort Commented May 4, 2012 at 21:42

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

A more C-ish/lazier way to write the comparator could be to just do return (strtotime($a) - strtotime($b));
So then I take it is impossible to do a sort like this in mongodb? Let me ask this then do you think it would be faster to use a function like this to sort like 100 reviews or to separate the reviews from the product collection and make a reviews collection?
@cKendrick I'm not an expert on MongoDB so I can't quite say that it's impossible. I posted this answer as an alternative solution. Although if I were you, I would definitely separate the reviews into another collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.