Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB에서 커서(Cursor)로 컬렉션을 반복 처리하는 방법

MongoDB에서 find() 메서드는 커서(cursor) 객체를 반환합니다. 이 커서를 활용하면 컬렉션에 저장된 문서들을 하나씩 순회하며 처리할 수 있습니다. 아래는 커서를 사용해 컬렉션을 반복하는 기본 문법입니다.

커서로 컬렉션 반복하기 – 기본 문법

var anyVariableName1;
var anyVariableName2 = db.yourCollectionName.find();
while (yourVariableName2.hasNext()) {
    yourVariableName1 = yourVariableName2.next();
    printjson(yourVariableName1);
};

핵심 동작 원리는 다음과 같습니다.

  • hasNext(): 커서에 아직 읽지 않은 문서가 남아 있는지 확인합니다.
  • next(): 커서의 현재 위치에서 다음 문서를 가져옵니다.
  • printjson(): 가져온 문서를 보기 좋게 JSON 형식으로 출력합니다.

샘플 컬렉션 생성

먼저 실습에 사용할 컬렉션을 만들고 문서를 삽입해 보겠습니다.

> db.loopThroughCollectionDemo.insertOne({"StudentName":"John","StudentAge":23});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c9ca81f2d6669774125247f")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Larry","StudentAge":21});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c9ca8272d66697741252480")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Chris","StudentAge":25});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c9ca8462d66697741252481")
}
> db.loopThroughCollectionDemo.insertOne({"StudentName":"Robert","StudentAge":24});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c9ca8632d66697741252482")
}

find() 메서드로 전체 문서 조회

find() 메서드와 pretty()를 함께 사용하면 컬렉션의 모든 문서를 정렬된 형태로 확인할 수 있습니다.

> db.loopThroughCollectionDemo.find().pretty();

위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.

{
    "_id" : ObjectId("5c9ca81f2d6669774125247f"),
    "StudentName" : "John",
    "StudentAge" : 23
}
{
    "_id" : ObjectId("5c9ca8272d66697741252480"),
    "StudentName" : "Larry",
    "StudentAge" : 21
}
{
    "_id" : ObjectId("5c9ca8462d66697741252481"),
    "StudentName" : "Chris",
    "StudentAge" : 25
}
{
    "_id" : ObjectId("5c9ca8632d66697741252482"),
    "StudentName" : "Robert",
    "StudentAge" : 24
}

커서를 이용한 실제 반복 처리 예제

이제 while 루프와 커서 메서드를 조합하여 컬렉션의 모든 문서를 하나씩 순회하는 쿼리를 작성해 보겠습니다.

> var allDocumentValue;
> var collectionName = db.loopThroughCollectionDemo.find();
> while (collectionName.hasNext()) {
...     allDocumentValue = collectionName.next();
...     printjson(allDocumentValue);
... }

실행 결과는 다음과 같습니다.

{
    "_id" : ObjectId("5c9ca81f2d6669774125247f"),
    "StudentName" : "John",
    "StudentAge" : 23
}
{
    "_id" : ObjectId("5c9ca8272d66697741252480"),
    "StudentName" : "Larry",
    "StudentAge" : 21
}
{
    "_id" : ObjectId("5c9ca8462d66697741252481"),
    "StudentName" : "Chris",
    "StudentAge" : 25
}
{
    "_id" : ObjectId("5c9ca8632d66697741252482"),
    "StudentName" : "Robert",
    "StudentAge" : 24
}

정리

이처럼 MongoDB 셸에서는 find()가 반환하는 커서에 대해 hasNext()next()를 반복 호출함으로써 컬렉션의 전체 문서를 순차적으로 처리할 수 있습니다. 대량의 데이터를 배치 단위로 가공하거나 조건별 로직을 적용할 때 유용하게 활용할 수 있으며, 자바스크립트 드라이버 환경에서도 동일한 패턴을 그대로 응용할 수 있습니다.