【问题标题】:Cursor Pagination using ObjectID / Timestamp field in MongoDB使用 MongoDB 中的 ObjectID / Timestamp 字段进行光标分页
【发布时间】:2021-09-22 17:53:38
【问题描述】:

我通过 last_message_id 字段对记录进行排序和分页,该字段采用 ObjectID(不是时间戳),但如果我们深入研究,它们都是相同的。

问题是如果我们使用时间戳进行分页,有些记录可能会在分页中被忽略,因为时间戳不是唯一的,它们可以重复。

在我的项目中有两个集合,“Rooms”和“Messages”。每当用户发送消息时,消息的关联房间将更新为消息的_id。 我这样做是因为我想向用户显示最近活跃的房间。

问题有解决办法吗?

房间:

_id room_name last_message_id
x General 612a8e6ab075cf9f2b8c6f9d
y Politics 612a8e6ab075cf9f2b8c6f9e

消息:

_id room_id text
612a8e6ab075cf9f2b8c6f9e y ...
612a8e6ab075cf9f2b8c6f9d x ...

【问题讨论】:

  • 什么问题,按非唯一字段排序或按您在标题中所说的 objectid/timestamp 排序?
  • @D.SM 我解决了我的问题,谢谢。

标签: mongodb


【解决方案1】:

我通过添加复合索引解决了这个问题:
['last_message_id', '_id'] 字段的顺序不得更改。

我们也可以使用 timestamp (created_at) 而不是 ObjectId (last_message_id)

示例:

// Pagination result: (limit 1)
[{_id: "613091804ae06dde2e507ff5", last_message_id: "612ff5e11d3130cc1fb1448e"}]

// to get more results:
// http://www.website.com/results?id=613091804ae06dde2e507ff5&last_message_id=612ff5e11d3130cc1fb1448e

// SudoQuery:
let id = req.query.id;
let last_message_id = req.query.last_message_id;
let query = {};

if (id && last_message_id) {
  query = {
    $or: [
      {
        last_message_id: {
          $lt: last_message_id 
        }
      },
      {
        last_message_id,
        _id: {
          $lt: id
        }
      }
    ]
  };
}

db.items.find(query).sort({last_message_id: -1, _id: -1}).limit(1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-09
    • 2021-10-25
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2020-02-17
    • 2011-01-04
    相关资源
    最近更新 更多