mongodb - mongoDB 中更新的聚合

标签 mongodb

我有一个包含许多相似结构化文档的集合,其中两个文档看起来像

输入:

{ 
    "_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/

相关文章:

node.js - findOneAndUpdate 在插入时返回 null?

java - GridFS 使用 Java 驱动程序仅检索一个文件范围

node.js - 无法连接到 mongolab.com

mongodb - 在 mongodb 的 hash 中查找

javascript - MongoDB 外壳 : Query BinData by Type

javascript - 如何在 mongo shell 中显示 "require(module)"

MongoDB:自定义端口和数据库路径不起作用

mysql - 我应该使用 mySQL 还是 MongoDB

mongodb - 在mongodb的聚合查询中,根据公共(public)字段将两个对象数组合并为一个数组

mysql - MongoDB、MySQL 或我的项目的第三种东西?