0

I have a Mongo collection for profile comments, which is structured like this:

{
    "_id": "",
    "comments": []
}

The id refers to the ID of the user from the profiles collection. For improved server power, I only want to show 10 comments per page. To do this, I use Mongo's $slice operator. Here is my code for the query.

mongoCols.profileComments.findOne({"_id":doc._id},{comments:{$slice:[(comPage-1)*10,10]}},function(err,doc) {

Here's the problem. I want to show the comments in reverse order, meaning that the newest comments are on the first page, and latest comments are on the last. I thought of a few solutions to this but they aren't very efficient.

1) I could retrieve the entire array, then use JavaScript (I'm using nodejs for this) to sort that array, then only take the 10 elements that I want. This seems inefficient because I'm asking Mongo to retrieve what is potentially a ton of elements from an array, when I only need 10.

2) I could make each comment a separate document, with a field saying what user the comment is for. I could then only find documents where the comment was sent to the requested user, and use the skip and limit options to only retrieve the 10 documents I want. My problem with this is that Mongo will have to go through almost every single comment every time you request for a user's comments. This seems inefficient, but it is my best solution so far.

I would prefer to keep the structure I currently have, but if I need to change for it to work, then I will comply.

Weastie
  • 157
  • 10
  • Possible duplicate of [Reverse array field in MongoDB](http://stackoverflow.com/questions/22053975/reverse-array-field-in-mongodb) – styvane Jul 09 '16 at 05:58
  • @SSDMS I don't like that solution, because wouldn't that require me to reverse the array every time a comment is added? – Weastie Jul 09 '16 at 14:27
  • I didn't say you should update your document. As I mentioned in the my answer on that question, the upcoming MongoDB release provides a the `$reverseArray` operator to do this. Btw it is available since version 3.3.4. Until then, your best bet is retrieve the last `n` documents by passing a negative value to `$slice` and use the [`reverse()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) method to reverse your array. – styvane Jul 09 '16 at 16:16

0 Answers0