我有一个包含许多类似结构化文档的集合,其中两个文档看起来像
输入:
{
"_id": ObjectId("525c22348771ebd7b179add8"),
"cust_id": "A1234",
"score": 500,
"status": "A"
"clear": "No"
}
{
"_id": ObjectId("525c22348771ebd7b179add9"),
"cust_id": "A1234",
"score": 1600,
"status": "B"
"clear": "No"
}
默认情况下clear,所有文档为"No",
要求:我必须将所有具有相同的文档的分数相加cust_id,前提是它们属于status "A"和status "B"。如果score超过了2000,那么我必须clear为"Yes"所有具有相同cust_id.
预期输出:
{
"_id": ObjectId("525c22348771ebd7b179add8"),
"cust_id": "A1234",
"score": 500,
"status": "A"
"clear": "Yes"
}
{
"_id": ObjectId("525c22348771ebd7b179add9"),
"cust_id": "A1234",
"score": 1600,
"status": "B"
"clear": "Yes"
}
是的,因为 1600+500 = 2100,并且 2100 > 2000。
我的方法:我只能通过聚合函数得到总和,但更新失败
db.aggregation.aggregate([
{$match: {
$or: [
{status: 'A'},
{status: 'B'}
]
}},
{$group: {
_id: '$cust_id',
total: {$sum: '$score'}
}},
{$match: {
total: {$gt: 2000}
}}
])
请建议我如何进行。