mongodb 如何按插入时间对 Meteor 集合进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13957691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:58:35  来源:igfitidea点击:

How can I sort a Meteor collection by time of insertion?

mongodbmeteormongodb-query

提问by squeezemylime

I am working on my first project using Meteor, and am having some difficulty with sorting.

我正在使用 Meteor 进行我的第一个项目,并且在排序方面遇到了一些困难。

I have a form where users enter aphorisms that are then displayed in a list. Currently the most recent aphorisms automatically display at the bottom of the list. Is there an easy way to have the most recent appear at the top of the list instead?

我有一个表单,用户可以在其中输入格言,然后将其显示在列表中。目前最新的格言会自动显示在列表的底部。有没有一种简单的方法可以让最新出现在列表的顶部?

I tried:

我试过:

   Template.list.aphorisms = function () {
    return Aphorisms.find({}, {sort: {$natural:1}});
};

And am stumped because the Meteor docs don't have many examples.

我很难过,因为 Meteor 文档没有很多例子。

回答by sohel khalifa

Assuming that the date_createdis in a valid date format along with the timestamp, You should insert the parsed value of date_createdusing Date.parse()javascript function, which gives the number of milliseconds between January 1, 1970 and date value contained in date_created.

假设date_created与时间戳一起采用有效的日期格式,您应该插入date_createdusing Date.parse()javascript 函数的解析值,该值给出了 1970 年 1 月 1 日和 中包含的日期值之间的毫秒数date_created

As a result of that, the most recently added record will contain greater value of date_createdthan the record inserted before it.

因此,最近添加的记录将包含date_created比之前插入的记录更大的值 。

Now when fetching the records, sort the cursor in descending order of the date_createdparameter as:

现在在获取记录时,按date_created参数的降序对游标进行排序:

 Aphorisms.find({}, {sort: {date_created: -1}});

This will sort records from newer to older.

这会将记录从新到旧排序。

Hope this helps.

希望这可以帮助。

回答by Samuel Ellis

I've found the following to be a cleaner solution:

我发现以下是一个更清洁的解决方案:

   Template.list.aphorisms = function () {
      return Aphorisms.find().fetch().reverse();
   };

Given that entire collection already exists in the reverse order that you would like, you can simply create an array of all the objects and reverse the order.

鉴于整个集合已经以您想要的相反顺序存在,您可以简单地创建一个包含所有对象的数组并反转顺序。