Node.js 聚合组上的Mongoose错误
我有这个模型:Node.js 聚合组上的Mongoose错误,node.js,mongodb,mongoose,mongodb-query,aggregation-framework,Node.js,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我有这个模型: var Chat = new Schema({ from: String, to: String, satopId: String, createdAt: Date }); var Chat = mongoose.model('Chat', Chat); 我想要执行一个查询来执行一个查询,该查询返回分组依据“收件人”和“发件人”字段创建的最大值。我试过: Chat.aggregate([ { $group: { _id:
var Chat = new Schema({
from: String,
to: String,
satopId: String,
createdAt: Date
});
var Chat = mongoose.model('Chat', Chat);
我想要执行一个查询来执行一个查询,该查询返回分组依据“收件人”和“发件人”字段创建的最大值。我试过:
Chat.aggregate([
{
$group: {
_id: '$to',
from: '$from',
createdAt: {
$max: '$createdAt'
}
}
},
{
$project: {
_id: 1,
createdAt: 1,
from: 1,
to: 1
}
}
], function(err, docs){
})
但这会产生以下错误:
必须将组聚合字段“from”定义为表达式
物体内部
我不明白这是什么意思。我怎样才能解决它
如果语句中的\u id
表达式需要某种类型的
假设您对将“唯一”分组键作为文档中的“收件人”字段的想法感到满意,那么您可能希望这样:
否则,如果您希望“两个”字段上都有“不同”的值,则它们都属于分组键的复合值:
Chat.aggregate([
{ "$group": {
"_id": {
"to": "$to",
"from": "$from"
},
"createdAt": { "$max": "$createdAt" }
}},
function (err, docs) {
// do something here
}
])
基本上就是这样。它要么是键的一部分,要么像SQL一样需要一个分组运算符
还请注意,您的断言并不是真正需要的,因为您已经在那里做了您要做的事情
Chat.aggregate([
{ "$group": {
"_id": {
"to": "$to",
"from": "$from"
},
"createdAt": { "$max": "$createdAt" }
}},
function (err, docs) {
// do something here
}
])