首页 > 解决方案 > 如何在猫鼬跳过和限制之前排序?

问题描述

const list = async function({
  end_cursor = 0
} = {}) {
  return await db.collection.find().sort({ _id: -1 }).skip(end_cursor).limit(50);
}

上面是我认为它应该工作的代码,但我发现它没有。这是显而易见的:

  let list1 = await list(0);
  list1 = list1.reduce((o, a)=>{
    let {
      _id
    } = a;
    o[_id] = true;
    return o;
  }, {});

  let list2 = await list(50);
  for (let i of list2) {
    let {
      _id
    } = i;
    if (list1[_id]) {
      console.log('repeated');
      break;
    }
  }

如果db.collection.find().sort({ _id: -1 }).skip(end_cursor).limit(50)有效, list1 和 list2 应该有唯一_id的 s,但他们没有,而是控制台输出repeat

标签: mongoose

解决方案


您可以根据您的要求使用聚合。

db.collection.aggregate([
  {$sort: {_id: -1}},
  {$skip: end_cursor}, //value should be a positive integer
  {$limit: 50}
]);

推荐阅读