【问题标题】:Meteor collection sort by $size issue流星集合按 $size 问题排序
【发布时间】:2016-06-03 11:08:49
【问题描述】:

这是关于 cmets 的好恶。我想按相似度对 cme​​ts 进行排序,因此将首先出现具有更多赞的评论。问题是不喜欢的 cmets 比没有不喜欢的 cmets 出现在前面。

我想要什么:

  • 评论 A:1 喜欢 0 不喜欢
  • 评论 B:0 喜欢 0 不喜欢
  • 评论 C:0 喜欢 1 不喜欢

我实际上得到了什么:

  • 评论 A:1 喜欢 0 不喜欢
  • 评论 C:0 喜欢 1 不喜欢
  • 评论 B:0 喜欢 0 不喜欢

我对我的流星助手的 mongo 查询:

Missatges.find({ topic: 'xxx' }, { sort: { like:{ $size: -1}, dislike:{ $size: 1}, date: -1 } }).fetch();

请注意,我使用 $size 是因为喜欢和不喜欢是用户 _id 的数组。 这是我的评论架构:

author: {
    type: String

},
authorId: {
    type: SimpleSchema.RegEx.Id
}
isAnswer: {
    type: Boolean
},
parentId: {
    type: SimpleSchema.RegEx.Id,
    optional: true
},
date: {
    type: Date
},
topic: {
    type: String
},
likes: {
    type: [SimpleSchema.RegEx.Id]
},
dislikes: {
    type: [SimpleSchema.RegEx.Id]
},
answers: {
    type: [SimpleSchema.RegEx.Id],
    optional: true
},
text: {
    type: String,
    max: 900,        
}

【问题讨论】:

  • 请展示您的评论模型设计
  • 它返回的结果是您正在使用的查询应该返回的方式。
  • 也许是我的英语,也许是你的……但抱歉,我不明白你的评论@titi23
  • 运行查询得到的结果是正确的。这就是查询应该返回的方式。希望现在很清楚。

标签: mongodb meteor


【解决方案1】:

根据this question 的答案,您不能使用$size 在mongo 中进行排序。一种解决方案是fetch 匹配文档和sort 在帮助程序中。这是一个示例(请注意,这是未经测试的,可能需要一些调整):

Template.something.helpers({
  sortedThings: function () {
    return Missatges
      .find({ topic: 'xxx' })
      .fetch()
      .sort(function (b, a) {
        var al = a.likes.length;
        var ad = a.dislikes.length;
        var bl = a.likes.length;
        var bd = a.dislikes.length;
        var d1 = a.date;
        var d2 = b.date;

        // compare by likes
        if (al > bl) return 1;
        if (al < bl) return -1;

        // compare by dislikes
        if (ad < bd) return 1;
        if (ad > bd) return -1;

        // compare by date
        if (d1 > d2) return 1;
        if (d1 < d2) return -1;

        // they are equal
        return 0;
      });
  },
});

【讨论】:

  • 一旦this issue 完全解决,应该可以将第二个参数的sort 属性中的自定义排序函数传递给find() 本身(我打算尽快提交PR) .
  • 谢谢大卫,不过,最后,我选择了您提供给我的链接上提供的解决方案。我在模型中添加了 2 个数字字段:nLike 和 nUnlikes。即使在我拥有的其他用例中,它也会变得更加方便
猜你喜欢
  • 2015-01-19
  • 1970-01-01
  • 2015-01-24
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多