在mongoDB中进行更新聚合 [英] Aggregation with update in mongoDB
问题描述
我有一个包含许多相似结构化文档的集合,其中两个文档看起来像
I've a collection with many similar structured document, two of the document looks like
输入:
{
"_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"
By default the clear
for all document is "No"
,
要求:我必须添加具有相同cust_id
的所有文档的得分,前提是它们属于status
"A"
和status
"B"
.如果score
超过2000
,那么对于具有相同cust_id
的所有文档,我必须将clear
属性更新为"Yes"
.
Req: I have to add the score of all documents with same cust_id
, provided they belong to status
"A"
and status
"B"
. If the score
exceeds 2000
then I have to update the clear
attribute to "Yes"
for all of the document with the same 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.
Yes because 1600+500 = 2100, and 2100 > 2000.
我的方法: 我只能通过聚合函数获取总和,但无法更新
My Approach: I was only able to get the sum by aggregate function but failed at updating
db.aggregation.aggregate([
{$match: {
$or: [
{status: 'A'},
{status: 'B'}
]
}},
{$group: {
_id: '$cust_id',
total: {$sum: '$score'}
}},
{$match: {
total: {$gt: 2000}
}}
])
请建议我如何进行.
推荐答案
在经历了很多麻烦之后,尝试使用mongo shell,我终于为我的问题找到了解决方案.
After a lot of trouble, experimenting mongo shell I've finally got a solution to my question.
伪代码:
# 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});
}
)
如果您对同一问题有不同的解决方案,请发表评论.
Please comment, if you have any different solution for the same question.
这篇关于在mongoDB中进行更新聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!