【问题标题】:mongoose - sort by array lengthmongoose - 按数组长度排序
【发布时间】:2012-07-21 04:33:10
【问题描述】:

我有这个架构

var PostSchema = new Schema({
    title: {type: String, trim: true}
  , description: {type: String, trim: true}
  , votes: [{ type: Schema.ObjectId, ref: 'User' }]
})

我想根据投票对帖子进行排序,即我需要按数组长度排序。

尝试了常规方法,但不起作用

PostSchema.statics.trending = function (cb) {
  return this.find().sort('votes', -1).limit(5).exec(cb)
}

有什么帮助吗?

我使用的猫鼬版本是 2.7.2

【问题讨论】:

    标签: mongodb sorting mongoose


    【解决方案1】:

    你不能直接这样做。为了能够对数组长度进行排序,您必须将其保存在一个单独的字段中(votes_count 或其他),并在您向/从votes 推/拉元素时更新它。

    然后您对 votes_count 字段进行排序。如果你也索引它,查询会更快。

    【讨论】:

    • 如何查询?
    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 2019-10-27
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多