Mongodb/sails find():带分页的不同记录

Mongodb/sails find(): distinct records with pagination

场景:

文档需要抓取,页数限制为 20 ,按降序排列。 返回的结果需要是唯一的( id, title etc , based on a 属性)

考虑第 1 页上的项目 A 在第 2 页上有重复项的可能性。

是否有可以处理这种情况的查询?

在 Sails waterline 中似乎不可能,但我想知道对 mongo 的本机调用是否可以解决这个问题。

我不认为 mongo 可以在这里做你想做的事。看起来你可以使用 mongo 的 distinct command to get distinct values of a given property across a collection, or across the result of a query (and sails exposes raw mongo queries via .native).

但是,如果您想要整个代表 object,而不仅仅是具有独特性的单个 属性,这可能没有用。它还不允许您以保证一定数量的不同值的方式进行查询。

我认为如果它必须工作,你将被迫在代码中工作。一种丑陋的方法是获取 "more than enough" 记录(30?100?)以合理确定 20 个不同的值,然后循环选择直到获得 20。要实现分页,您可以使用您所在的字段排序(如果该字段也是唯一字段,这将起作用。

示例 api 调用 collection 字段 titlepopularity(例如),我们想要不同的标题,并按 popularity DESC:(此代码将在某些控制器的 module.exports 中)

getMoreRecords: function(req, res) {
    var foundTitles = req.param('foundTitles'); // an array of titles we already have
    var lowestPop = req.param('lowestPop'); // the lowest popularity already retrieved
    Record.find({
        title: {'!': foundTitles},
        popularity: {'<': lowestPop}
    }).limit(100).sort('popularity DESC').exec(function(err, records) {
        // do the error handling...
        var filteredRecords = records.filter(function(rec, idx, arr) {
            return arr.indexOf(rec) === idx;
        });
        // filteredRecords is guaranteed to contain records with unique, unseen titles in popularity desc order
        // it could contain any number however
        return res.json(filteredRecords.slice(0,20));
    });
}

这需要为每个新页面将所有已找到的标题发回服务器。为避免这种情况,您可以这样做 client-side,但它会变得越来越复杂。

一般来说,我会建议保留 "more than enough" 条记录 client-side(例如,多页价值),并在需要更多时查询,也许在几页之后。我会在客户端对 already-seen 标题进行任何过滤,而不是像我在此处显示的那样在服务器上进行过滤。