Node.js Mongo DB使用聚合将较新的结果放在查询的顶部

Node.js Mongo DB使用聚合将较新的结果放在查询的顶部,node.js,mongodb,Node.js,Mongodb,我从一个集合中提取了一系列结果。我想先显示过去30天内的所有条目,然后按下载次数对其余条目进行排序。一次只加载10个,滚动时加载更多 Data.aggregate([ {'$match': match}, {"$sort": {downloads : -1, createdAt: -1}}, {"$skip": page * entriesPerPage}, {"$limit": entriesPerPage}, {"$lookup":

我从一个集合中提取了一系列结果。我想先显示过去30天内的所有条目,然后按下载次数对其余条目进行排序。一次只加载10个,滚动时加载更多

Data.aggregate([
      {'$match': match},
      {"$sort": {downloads : -1, createdAt: -1}},
      {"$skip": page * entriesPerPage},
      {"$limit": entriesPerPage},
      {"$lookup": {
        "from": "examples",
        "localField": "_id",
        "foreignField": "docId",
        "as": "examples"
      }},
    ]).exec(function(err, docs) {});
现在我正试图通过获取所有结果,然后将它们分成两个数组来手动完成,但现在我意识到这意味着我也必须手动完成$skip部分。也不是很好,我必须加载并查看所有结果

作为聚合查询的一部分,有没有一种方法可以做到这一点

编辑:这是一个文档:

{ "_id" : ObjectId("58ddc3f76853d8286b22bc7b"), 
"updatedAt" : ISODate("2017-11-12T09:39:22.031Z"), 
"createdAt" : ISODate("2017-03-31T02:50:31.631Z"), 
"name" : "Dragon", 
"slug" : "dragon", 
"description" : "A dragon is a legendary creature, typically scaled or fire-spewing and with serpentine, reptilian or avian traits, that features in the myths of many cultures around world.", 
"downloads" : 18, 
"type" : "monster", 
"numberOfColors" : 16, "__v" : 1, 
"tags" : [ "monster" ] }

目前大约有100人。同样,我想先显示createdAt在过去30天内的所有位置,然后按下载次数显示其余位置。

您需要一个临时帮助器字段,您可以使用pipeline stage(或MongoDB版本<3.4)获取该字段:


你可以发布一个示例文档吗?更新了我的帖子,这很有意义,我会尝试一下。我改进了答案,使文档的第一部分(在过去三十天内创建)现在可以很好地按日期排序。我使用了$project,因为我有3.2版本,而且效果很好
var thirtyDaysInMilliSeconds = 30 * 24 * 60 * 60 * 1000;

Data.aggregate([
      {"$match": match},
      {'$addFields': { // let's add a field that contains either 0 or 1 depending on whether the "createdAt" value is greater than "today - 30 days"
          "sortHelperField": { $cond: [ { $gt: [ "$createdAt", { $subtract: [ new Date(), thirtyDaysInMilliSeconds ] } ] }, "$createdAt", 0] }
      }},
      {"$sort": {"sortHelperField": -1, downloads: -1}}, // then we can sort by that field, too, and make it the field with the highest priority
      /* all the rest of your stages can stay the way the are */
    ]);