[MONGODB] MongoDB의에서 업데이트의 집계
MONGODBMongoDB의에서 업데이트의 집계
나는 많은 유사한 구조화 된 문서와 문서 모양과 같은 두 가지 컬렉션을했습니다
입력:
{
"_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 모든 문서의 점수를 추가해야합니다, 그들은 상태 "A"상태 "B"에 속하는 제공. 점수가 2000을 초과하면 나도 같은 CUST_ID와 문서의 모든 "예"에 clear 속성을 업데이트해야합니다.
예상 출력 :
{
"_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 = 2100 + 500, 및> 2000 2100 있기 때문이다.
내 접근 : 난 단지 집계 함수에 의해 합계를 얻을 수 있었지만 업데이트에 실패
db.aggregation.aggregate([
{$match: {
$or: [
{status: 'A'},
{status: 'B'}
]
}},
{$group: {
_id: '$cust_id',
total: {$sum: '$score'}
}},
{$match: {
total: {$gt: 2000}
}}
])
나는 계속 어떻게 저를 제안하십시오.
해결법
-
==============================
1.쉘 몽고 실험 문제를 많이, 후에 나는 마침내 내 질문에 대한 해결책을 가지고있다.
쉘 몽고 실험 문제를 많이, 후에 나는 마침내 내 질문에 대한 해결책을 가지고있다.
의사 코드 :
# 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}); } )
같은 질문에 대한 어떤 다른 해결책이있는 경우, 의견을 주시기 바랍니다.
-
==============================
2.당신은 두 단계로이 작업을 수행 할 필요가 :
당신은 두 단계로이 작업을 수행 할 필요가 :
이미 첫 번째 부분에 대한 좋은 솔루션이있다. 두 번째 부분은 별도의 업데이트로 데이터베이스 () 호출을 구현해야한다.
의사 코드 :
# Get list of customers using the aggregation framework cust_to_clear = db.col.aggregate( {$match:{$or:[{status:'A'},{status:'B'}]}}, {$group:{_id:'$cust_id', total:{$sum:'$score'}}}, {$match:{total:{$gt:2000}}} ) # Loop over customers and update "clear" to "yes" for customer in cust_to_clear: id = customer[_id] db.col.update( {"_id": id}, {"$set": {"clear": "Yes"}} )
당신은 모든 고객에 대한 데이터베이스 호출을하기 때문에이 적합하지 않습니다. 자주 작동 이런 종류의 작업을 수행해야하는 경우, 각 문서의 총 점수를 포함하도록 스키마를 수정할 수 있습니다. (이 응용 프로그램에 의해 관리되어야 할 것이다.)이 경우, 당신은 하나의 명령으로 업데이트를 할 수 :
db.col.update( {"total_score": {"$gt": 2000}}, {"$set": {"clear": "Yes"}}, {"multi": true} )
-
==============================
3.몽고 4.2로 집계 파이프 라인이 사용하여 업데이트를 수행 할 수있게되었습니다. 예제 2는 조건부 업데이트를 어떻게 예제가 실려있다 :
몽고 4.2로 집계 파이프 라인이 사용하여 업데이트를 수행 할 수있게되었습니다. 예제 2는 조건부 업데이트를 어떻게 예제가 실려있다 :
db.runCommand( { update: "students", updates: [ { q: { }, u: [ { $set: { average : { $avg: "$tests" } } }, { $set: { grade: { $switch: { branches: [ { case: { $gte: [ "$average", 90 ] }, then: "A" }, { case: { $gte: [ "$average", 80 ] }, then: "B" }, { case: { $gte: [ "$average", 70 ] }, then: "C" }, { case: { $gte: [ "$average", 60 ] }, then: "D" } ], default: "F" } } } } ], multi: true } ], ordered: false, writeConcern: { w: "majority", wtimeout: 5000 } } )
또 다른 예:
db.c.update({}, [ {$set:{a:{$cond:{ if: {}, // some condition then:{} , // val1 else: {} // val2 or "$$REMOVE" to not set the field or "$a" to leave existing value }}}} ]);
-
==============================
4.MongoDB는 2.6., 동일한 명령 응집 질의의 결과를 기록 할 수있을 것이다.
MongoDB는 2.6., 동일한 명령 응집 질의의 결과를 기록 할 수있을 것이다.
자세한 내용은 여기 : http://docs.mongodb.org/master/reference/operator/aggregation/out/
from https://stackoverflow.com/questions/19384871/aggregation-with-update-in-mongodb by cc-by-sa and MIT license
'MONGODB' 카테고리의 다른 글
[MONGODB] 스파 스 인덱스와 몽고에 null 값 (0) | 2019.12.24 |
---|---|
[MONGODB] _id 필드가없는 mongoexport (0) | 2019.12.24 |
[MONGODB] MongoDB를이 - 코드 종료 : 62 (0) | 2019.12.24 |
[MONGODB] 새로운 분야에 배열 프로젝트의 첫 번째 항목 (MongoDB를 집계) (0) | 2019.12.24 |
[MONGODB] MongoDB의 쿼리에 $에 전달 된 매개 변수의 최대 수는 무엇입니까? (0) | 2019.12.24 |