MongoDB와 함께 C# Record types 사용하기

발행: (2026년 2월 13일 오전 01:42 GMT+9)
6 분 소요
원문: Dev.to

Source: Dev.to

MongoDB Guests

이 게스트 저자 글은 Markus Wildgruber – Managing Director/Cloud Architect, sevantage software GmbH에 의해 작성되었습니다.

Introduction

C# 9.0이 도입될 때 주요 초점은 불변 타입에 대한 지원을 강화하는 것이었습니다. 이 프로그래밍 패턴은 부수 효과가 줄어들어 동시 실행에 대한 지원을 향상시키고 코드를 이해하기 쉽게 만드는 것을 목표로 합니다. 이전에도 수동으로 불변 타입을 정의할 수 있었지만, C# 9.0에서는 record 키워드가 도입되어 불변 타입을 손쉽게 정의할 수 있게 되었습니다. 이 “구문 설탕”은 타입에 다음과 같은 기능도 추가합니다:

  • record 타입은 IEquatable 구현과 값 동등성을 처리하는 다양한 메서드를 자동으로 제공하므로, 이러한 메서드를 직접 구현할 필요가 없습니다. 애플리케이션 코드에서 MongoDB 문서를 모든 속성으로 비교하는 경우는 드물지만, 단일 객체 전체를 비교할 수 있다면 각 속성 값을 개별적으로 검사하는 것보다 단위 테스트를 훨씬 읽기 쉽게 만들 수 있습니다.
  • record 타입은 속성 값에 기반한 GetHashCode 구현을 제공합니다. 대부분의 record 타입은 위치 매개변수만을 사용하고 이 매개변수는 불변이므로, 객체 초기화 후 해시 코드가 변경되지 않습니다. 이는 객체를 사전의 키로 사용하거나 해시 집합에 추가할 때 특히 중요합니다. 해시 코드가 객체의 값과 일치하지 않아 컬렉션에서 항목이 사라지는 추적하기 어려운 버그를 방지할 수 있습니다.
  • recordToString 메서드는 객체의 속성을 의미 있게 표시합니다. 디버깅 시 큰 도움이 되는 작은 변화입니다.

record 타입의 특성에 대한 전체 개요는 Microsoft 웹사이트의 문서를 참고하세요.

레코드 POCO 정의

전통적인 class 타입에 비해 record 정의의 또 다른 장점은 훨씬 간결하다는 점입니다:

using MongoDB.Bson;

public record Movie(
    ObjectId Id,
    string Title,
    string Plot
);

위 예시와 같이 대부분의 record 타입은 괄호 안에 속성을 직접 나열하는 기본 생성자를 사용합니다. 컴파일러는 이 정의를 다음과 유사한 클래스 형태로 변환합니다:

using MongoDB.Bson;

public class Movie : IEquatable
{
    public Movie(ObjectId id, string title, string plot)
    {
        Id = id;
        Title = title;
        Plot = plot;
    }

    public ObjectId Id { get; init; }
    public string Title { get; init; }
    public string Plot { get; init; }

    // …
}

선언적 매핑

이 접근 방식을 사용할 때는 MongoDB 속성의 선언적 매핑을 생성된 속성에 적용되도록 조정해야 합니다. 예를 들어, Id를 MongoDB에서는 ObjectId로 저장하고 모델에서는 string으로 노출하고 싶다면 property 속성 대상 지정자를 적용해야 합니다:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

[BsonIgnoreExtraElements]
public record Movie(
    [property: BsonRepresentation(BsonType.ObjectId)] string Id,
    [property: BsonElement("title")] string Title,
    [property: BsonElement("plot")] string Plot
);

수동 매핑

클래스 맵을 수동으로 생성하고 싶다면 (자세한 내용은 MongoDB C# Driver documentation을 참고하세요), 이것도 지원됩니다:

BsonClassMap.RegisterClassMap(classMap =>
{
    classMap.SetIgnoreExtraElements(true);
    classMap.MapMember(p => p.Id)
            .SetSerializer(new StringSerializer(MongoDB.Bson.BsonType.ObjectId));
    classMap.MapMember(p => p.Title).SetElementName("title");
    classMap.MapMember(p => p.Plot).SetElementName("plot");
});

모두 합쳐서

다음 파일 기반 C# 앱은 record 타입을 기반으로 하는 MongoDB에서 데이터를 액세스할 때 변경이 필요 없음을 보여줍니다:

#:package MongoDB.Driver@*
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;

string connStr = "mongodb://localhost:27017";
string databaseName = "sample_mflix";
int limit = 5;

IMongoClient client = new MongoClient(connStr);
IMongoDatabase database = client.GetDatabase(databaseName);
IMongoCollection moviesCollection = database.GetCollection("movies");

foreach (Movie movie in moviesCollection
                         .Find(FilterDefinition.Empty)
                         .Limit(limit)
                         .ToEnumerable())
{
    Console.WriteLine(movie);
}

[BsonIgnoreExtraElements]
public record Movie(
    [property: BsonRepresentation(BsonType.ObjectId)] string Id,
    [property: BsonElement("title")] string Title,
    [property: BsonElement("plot")] string Plot
);

Bottom line & next steps

Records make the model layer of a MongoDB‑based C# application both leaner and safer. They give you immutable value semantics for free, remove boiler‑plate code, and provide reliable equality, hashing, and debugging support. Consider adopting record types for your domain models and explore further MongoDB driver features such as custom serializers or conventions to fully leverage the benefits of immutable data structures.

Boilerplate code for equality checking and add a ToString implementation. Be sure to use the property attribute target to apply MongoDB serialization attributes to properties.

Give it a try – replace a few of your class‑based POCOs with records. We love it when you share your experience – if you hit a pitfall or discover a pattern that worked well, drop a comment so we can all learn.

Happy coding!

0 조회
Back to Blog

관련 글

더 보기 »

Windows Native Development를 고쳤다

빌드 요구 사항: Visual Studio 설치 > 아직 이 사실을 모를 정도로 운이 좋다면, 부러워합니다. 안타깝게도 이제는 보로미어조차도 알고 있습니다… 잘 표현했네요,…

바위 ✊ 종이 ✋ 가위 ✌️

WebForms Core란 무엇인가? WebForms Core https://github.com/webforms-core 은 Elanat https://elanat.net/ 에서 만든 새로운 멀티플랫폼 기술로, 경쟁하도록 설계되었습니다.

특수 문자 | C++ 초보

String와 특수 문자 Escape 문자는 문자열이나 텍스트 안에서 특수 명령·문자를 쓰기 위해 사용됩니다. ' ' – 따옴표 안에 따옴표를 ...