聚集组上的Mongoose错误

我有这个模型:

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

我想做一个查询来做一个查询,返回最大的创build在分组来自和来自领域。 我试着用:

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

但是这会产生这个错误:

组合字段“from”必须定义为对象内的expression式

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

谢谢

如果$group语句中的_idexpression式需要某种“分组操作符” ,则任何“外部”。

假设你对“唯一”分组键在文档中的“to”字段的想法感到满意,那么你可能需要像$first这样的东西:

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

否则,如果你想在“两个”字段上有“不同的”值,那么它们都属于分组键值的复合值:

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

这基本上是如何工作的。 要么它是键的一部分,要么像SQL一样需要分组操作符。

另外请注意,您的$project断言并不是真正需要的,因为$group已经做了你在那里的要求。