mongodb聚合$ group $ sort

时间:2014-07-06 18:23:14

标签: node.js mongodb mongoose

我有一个这样的星型模式:

Schema = mongoose.Schema
  user:
    type: mongoose.Schema.Types.ObjectId
    ref: "User"
  mod:
    type: mongoose.Schema.Types.ObjectId
    ref: "Mod"
  time_bucket:
    raw: Date
    hour: String
    day: String
    week: String
    month: String
    quarter: String
    year: String   

Schema.virtual("date").get () ->
  return time_bucket[0].raw
.set (date) ->
  date = new Date date
  @time_bucket =
    raw:      date
    hour:     "#{date.getFullYear()}-#{date.getMonth()}-#{date.getDate()}-#{date.getHours()}"
    day:      "#{date.getFullYear()}-#{date.getMonth()}-#{date.getDate()}"
    week:     "#{date.getFullYear()}-#{date.getMonth()}-#{date.getWeek()}"
    month:    "#{date.getFullYear()}-#{date.getMonth()}"
    quarter:  "#{date.getFullYear()}-#{date.getQuarter()}"
    year:     "#{date.getFullYear()}"

mod字段对应一个mod,它可以有很多星。

我正在努力获得这样的热门模式:

Star.aggregate [
    {
      $limit : 6
    }
    {
      $match:
        "time_bucket.month": "#{date.getFullYear()}-#{date.getMonth()}"
    }
    {
      $group:
        _id: "$mod"
        stars:
          "$sum": 1
    }
    {
      $sort : {
        "stars": -1
        }
    }

  ], (err, docs) ->
    Star.populate docs,
      path: "_id",
      model: "Mod",
      select: "slug name summary author created lastUpdated"
    , (err, docs) ->
      data.trendingMods = docs

但这不起作用。我可以在一周内获得6个mod的星数,但是我无法对它们进行排序:(。如何对它们进行排序以获得比其他星星更多的明星? < / p>

1 个答案:

答案 0 :(得分:1)

作为@NeilLunn,$limit在开头,而它应该在$group之后:

  Star.aggregate [
    {
      $match:
        "time_bucket.month": "#{date.getFullYear()}-#{date.getMonth()}"
    }
    {
      $group:
        _id: "$mod"
        stars:
          "$sum": 1
    }
    {
      $limit : 6
    }
    {
      $sort : {
        "stars": -1
        }
    }

  ], (err, docs) ->

谢谢!