我从一个集合中提取了大量结果。我想先显示过去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个。我想再次显示创建过去30天内的所有内容,然后按下载次数显示其余内容。
答案 0 :(得分:1)
您将需要一个临时帮助字段,您可以使用$addFields管道阶段(或$project处理MongoDB版本< 3.4)来获取该字段:
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 */
]);