MongoDB에서 업데이트 작업 후 실제로 몇 개의 문서가 수정되었는지 확인해야 하는 경우가 자주 있습니다. 이를 위해서는 runCommand 메서드와 함께 getlasterror 명령을 사용하면 됩니다. getlasterror는 가장 최근에 실행된 쓰기(write) 작업에 대한 상세 정보를 반환하며, 그중 n 필드가 업데이트된 문서의 개수를 나타냅니다.
1. 샘플 컬렉션 생성 및 문서 삽입
먼저 테스트용 컬렉션을 만들고 문서를 여러 개 삽입하겠습니다.
> db.getNumberOfUpdatedDocumentsDemo.insertOne({"StudentName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca28c1d6304881c5ce84bad")
}
> db.getNumberOfUpdatedDocumentsDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca28c226304881c5ce84bae")
}
> db.getNumberOfUpdatedDocumentsDemo.insertOne({"StudentName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca28c276304881c5ce84baf")
}
> db.getNumberOfUpdatedDocumentsDemo.insertOne({"StudentName":"Ramit"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca28c366304881c5ce84bb0")
}
> db.getNumberOfUpdatedDocumentsDemo.insertOne({"StudentName":"Adam"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca28c436304881c5ce84bb1")
}find() 메서드를 사용해 컬렉션의 모든 문서를 조회해 보겠습니다.
> db.getNumberOfUpdatedDocumentsDemo.find().pretty();
위 쿼리는 다음과 같은 결과를 출력합니다.
{ "_id" : ObjectId("5ca28c1d6304881c5ce84bad"), "StudentName" : "David" }
{ "_id" : ObjectId("5ca28c226304881c5ce84bae"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5ca28c276304881c5ce84baf"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5ca28c366304881c5ce84bb0"), "StudentName" : "Ramit" }
{ "_id" : ObjectId("5ca28c436304881c5ce84bb1"), "StudentName" : "Adam" }총 5개의 문서가 저장되어 있는 것을 확인할 수 있습니다.
2. 문서 업데이트 및 업데이트된 개수 조회
이제 모든 문서의 StudentName 값을 "Carol"로 변경하는 업데이트 쿼리를 실행합니다. 네 번째 인자인 multi 옵션을 true로 설정하여 조건에 일치하는 모든 문서를 한 번에 수정합니다.
> db.getNumberOfUpdatedDocumentsDemo.update({}, {$set : {"StudentName" : "Carol"}}, true, true);
WriteResult({ "nMatched" : 5, "nUpserted" : 0, "nModified" : 5 })업데이트 직후 runCommand와 getlasterror를 사용해 업데이트된 문서의 개수를 조회합니다.
> db.runCommand( "getlasterror" );
결과에서 n : 5 값이 출력되며, 이는 5개의 문서가 성공적으로 업데이트되었음을 의미합니다.
{
"connectionId" : 4,
"updatedExisting" : true,
"n" : 5,
"syncMillis" : 0,
"writtenTo" : null,
"err" : null,
"ok" : 1
}주요 필드의 의미는 다음과 같습니다.
- n: 마지막 쓰기 작업으로 영향을 받은 문서의 개수
- updatedExisting: 기존 문서가 업데이트되었는지 여부
- err: 오류 발생 시 해당 메시지, 정상일 경우 null
- ok: 명령 자체의 성공 여부 (1 = 성공)
3. 업데이트 결과 확인
다시 전체 문서를 조회하여 실제로 변경이 적용되었는지 확인해 보겠습니다.
> db.getNumberOfUpdatedDocumentsDemo.find().pretty();
모든 문서의 StudentName이 "Carol"로 변경된 것을 볼 수 있습니다.
{ "_id" : ObjectId("5ca28c1d6304881c5ce84bad"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5ca28c226304881c5ce84bae"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5ca28c276304881c5ce84baf"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5ca28c366304881c5ce84bb0"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5ca28c436304881c5ce84bb1"), "StudentName" : "Carol" }참고: 최신 MongoDB 버전에서의 대안
getlasterror는 구버전(3.x 이전) MongoDB에서 주로 사용되던 방식으로, 현재는 deprecated 상태입니다. MongoDB 3.x 이상에서는 update() 실행 시 반환되는 WriteResult 객체의 nModified, nMatched 필드만으로도 업데이트된 문서 수를 바로 확인할 수 있으므로, 최신 환경에서는 별도의 runCommand 호출 없이 WriteResult를 활용하는 것이 권장됩니다.