我编写了一个聚合函数来计算Message。基于消息状态。
exports.countRecords = function(req, res) {
Message.aggregate([{
$group: {
_id: "$message_status",
count: {
$sum: 1
}
}
}, {
$sort: {
_id: 1
}
}], function(err, result) {
if (err) {
console.log(err);
return;
}
console.log(result);
res.jsonp(result);
});
};
现在我需要添加一个条件,只有当channel_message_ID和channel_thread_Id相等时才计数,所以我修改了如下的逻辑:
Message.aggregate([{
$match: {
channel_message_ID: { $eq: ["$channel_message_ID", "$channel_thread_Id"]}
}},
{$group: {
_id: "$message_status",
count: {
$sum: 1
}
},
}, {
$sort: {
_id: 1
}
}], function(err, result) {
if (err) {
console.log(err);
return;
}
console.log(result);
res.jsonp(result);
});
};
根本没有工作。在此先感谢。
答案 0 :(得分:1)
尝试以下解决方案:
$项目:
Message.aggregate([{
{"$project": {
"channel_message_ID":1,
"channel_thread_Id":1,
"message_status": 1,
"cond": {"$eq":["$channel_message_ID","$channel_thread_Id"]}
}
},
{"$match":{"cond": true}},
{$group: {
_id: "$message_status",
count: {
$sum: 1
}
},
}, {
$sort: {
_id: 1
}
}], function(err, result) {
if (err) {
console.log(err);
return;
}
console.log(result);
res.jsonp(result);
});
答案 1 :(得分:0)
您需要在聚合管道的第一阶段向文档添加新字段,这可以通过使用[$ addFields]来完成 (https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/)阶段
{ "$addFields" : { "idMatch" : { "$eq" : [ "$channel_message_ID" , "$channel_thread_Id" ] } } }
这将为流经管道的文档创建一个新字段,告诉我们两个字段是否匹配。然后我们可以将其推送到$match阶段
{ $match: { "idMatch" : true } }
然后你可以运行$ group的其余部分:
{ "$group" : { "_id" : "$message_status", "count" : { "$sum" : 1 } } }
然后排序阶段:
{ "$sort" : { "_id" : 1 } }
例如,如果我们将以下文档添加到mongodb集合中:
db.test.insertMany([{
message_status: "In Progress",
channel_thread_Id: "A",
channel_message_ID: "A"
},
{
message_status: "Completed",
channel_thread_Id: "A",
channel_message_ID: "A"
},
{
message_status: "In Progress",
channel_thread_Id: "A",
channel_message_ID: "B"
},
{
message_status: "Completed",
channel_thread_Id: "A",
channel_message_ID: "B"
}]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("599abef4f0cd60f52d67215a"),
ObjectId("599abef4f0cd60f52d67215b"),
ObjectId("599abef4f0cd60f52d67215c"),
ObjectId("599abef4f0cd60f52d67215d")
]
}
然后我们可以运行以下聚合查询:
db.test.aggregate([
{ "$addFields" : { "idMatch" : { "$eq" : [ "$channel_message_ID" , "$channel_thread_Id" ] } } },
{ $match: { "idMatch" : true } },
{ "$group" : { "_id" : "$message_status", "count" : { "$sum" : 1 } } },
{ "$sort" : { "_id" : 1 } }
]);
将返回
的预期结果{ "_id" : "Completed", "count" : 1 }
{ "_id" : "In Progress", "count" : 1 }