我有一个包含许多相似结构化文档的集合,其中两个文档看起来像
输入:
{
"_id": ObjectId("525c22348771ebd7b179add8"),
"cust_id": "A1234",
"score": 500,
"status": "A"
"clear": "No"
}
{
"_id": ObjectId("525c22348771ebd7b179add9"),
"cust_id": "A1234",
"score": 1600,
"status": "B"
"clear": "No"
}
默认情况下,所有文档的清除
为“否”
,
要求:我必须添加具有相同 cust_id
的所有文档的分数,前提是它们属于 status
"A"
和 状态
“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}
}}
])
请建议我如何继续。
最佳答案
经过很多麻烦,尝试 mongo shell 我终于找到了我的问题的解决方案。
伪代码:
# To get the list of customer whose score is greater than 2000
cust_to_clear=db.col.aggregate(
{$match:{$or:[{status:'A'},{status:'B'}]}},
{$group:{_id:'$cust_id',total:{$sum:'$score'}}},
{$match:{total:{$gt:500}}})
# To loop through the result fetched from above code and update the clear
cust_to_clear.result.forEach
(
function(x)
{
db.col.update({cust_id:x._id},{$set:{clear:'Yes'}},{multi:true});
}
)
如果您对同一问题有不同的解决方案,请评论。
关于mongodb - mongoDB 中更新的聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19384871/