Mongodb聚合跳过并限制了排序,使分页中出现重复记录

时间:2018-08-12 05:10:18

标签: mongodb sorting pagination aggregation-framework

我有以下查询,该查询首先对文档进行排序,然后跳过并限制10条记录,以下是我的查询:

db.getCollection('jobpostings').aggregate([
{"$match":{
    "expireDate":{"$gte": ISODate("2018-08-12T00:00:00.000Z")},
    "publishDate":{"$lt": ISODate("2018-08-13T00:00:00.000Z")},
    "isPublished":true,
    "isDrafted":false,
    "deletedAt":{"$eq":null},
    "deleted":false,
    "blocked":{"$exists":false}
}},
{"$lookup":{"from":"companies","localField":"company.id","foreignField":"_id","as":"companyDetails"}},
{"$match":{"companyDetails":{"$ne":[]}}},
{"$sort":{
    "isFeatured":-1,
    "refreshes.refreshAt":-1,
    "publishDate":-1
}},
{"$skip":0},
{"$limit":10},
{"$project":{
    "position":1,"summary":1,"company":1,"publishDate":1,
    "expireDate":{"$dateToString":{"format":"%Y-%m-%d","date":"$expireDate"}},
    "locations":1,"minimumEducation":1,"workType":1,"skills":1,"contractType":1,
    "isExtensible":1,"salary":1,"gender":1,"yearsOfExperience":1,"canApplyOnline":1,"number":1,
    "isFeatured":1,"viewsCount":1,
    "status":{"$cond":{
        "if":{"$and":[
            {"$lt":["$publishDate", ISODate("2018-08-13T00:00:00.000Z")]},
            {"$gt":["$publishDate", ISODate("2018-08-11T00:00:00.000Z")]}]},"then":"New",
        "else":{"$cond":{
            "if":{"$lt":["$publishDate",ISODate("2018-08-12T00:00:00.000Z")]},"then":"Old","else":"Future"}}}},
            "companyDetails.profilePic":1,"companyDetails.businessUnits":1,"companyDetails.totalRatingAverage":1,
            "expiringDuration":{"$floor":{"$divide":[{"$subtract":["$expireDate",ISODate("2018-08-12T00:00:00.000Z")]},
            86400000]}},
            "companyDetails.totalReviews":{"$size":{"$ifNull":[{"$let":{"vars":{
                "companyDetailOne":{"$arrayElemAt":["$companyDetails",0]}},"in":"$$companyDetailOne.reviews"}},[]]}}}}

])

如果我发表评论,则跳过并限制以下内容为我的结果: no limit

但是以下是我对skip = 0, limit = 10的搜索结果: first page

现在将以上skip=10, limit=10的结果与以下结果进行比较:突出显示的文档在第二页(skip=10, limit=10)中重复: second page

对于其他文档,其他页面中也存在同样的情况。

1 个答案:

答案 0 :(得分:2)

似乎您要排序的三个字段不是唯一的,因此在后续执行中顺序可能会有所不同。要解决此问题,您可以在$sort中添加其他字段。由于_id始终是唯一的,因此它可能是一个不错的选择。试试:

{"$sort":{
    "isFeatured":-1,
    "refreshes.refreshAt":-1,
    "publishDate":-1,
    "_id": -1
}}