聚合组上的猫鼬错误

Mongoose error on aggregate group

我有这个型号:

var Chat = new Schema({
    from: String,
    to: String,
    satopId: String,
    createdAt: Date
});
var Chat = mongoose.model('Chat', Chat);

我想查询 returns 在按往返字段分组时创建的最大值。我试过:

Chat.aggregate([
  {
    $group: {
      _id: '$to',
      from: '$from',
      createdAt: {
        $max: '$createdAt'
      }
    }
  },
  {
    $project: {
      _id: 1,
      createdAt: 1,
      from: 1,
      to: 1
    }
  }
], function(err, docs){

})

但这会产生这个错误:

the group aggregate field 'from' must be defined as an expression inside an object

我不明白这是什么意思。我该如何解决?

谢谢

任何 "outside" 如果 _id 表达式在某种 $group statement requires a "grouping operator" 中。

假设您对将 "sole" 分组键作为文档中的 "to" 字段的想法感到满意,那么您可能想要 $first:

    Chat.aggregate([
        { "$group": { 
            "_id": "$to", 
            "from": { "$first": "$from" }, 
            "createdAt": { "$max": "$createdAt" } 
        }}, 
        function (err, docs) {
            // do something here
        }
    ])

否则,如果您想要 "both" 字段上的 "distinct" 值,那么它们都属于分组键的复合值:

    Chat.aggregate([
        { "$group": { 
            "_id": {
                "to": "$to", 
                "from": "$from"
            },
            "createdAt": { "$max": "$createdAt" } 
        }}, 
        function (err, docs) {
            // do something here
        }
    ])

这基本上就是它的工作原理。它要么是密钥的一部分,要么是需要分组运算符的东西,就像 SQL.

另请注意,您的 $project assertion is not really required as $group 已经完成了您在那里的要求。