Docs Menu

Docs HomeC#/.NET

Work with POCOs

On this page

  • Overview
  • Create a POCO
  • Custom Serialization
  • Set Field Names
  • Select Type Representation
  • Set Field Order
  • Identify Id Property
  • Omit Empty Fields
  • Example
  • Additional Information
  • API Documentation

In this guide, you can learn about how you can use "Plain Old CLR/Class Objects", or POCOs, with the .NET/C# Driver for your operations and queries. POCOs are simple class objects that do not inherit features from any framework-specific base classes or interfaces. We recommend using POCOs in your C# code to adhere to idiomatic driver usage and achieve the best performance.

You should read this guide if you want to learn more about how to use POCOs with the .NET/C# Driver or if you need to adjust the driver's default field mapping behavior.

You can create a POCO by defining a simple class that does not implement interfaces or extend classes from a framework. When you execute an operation such as a read or write using a POCO, the driver internally serializes, or converts, the POCO to BSON.

Select the POCO or BSON tab to see how the driver serializes a sample POCO to BSON:

You can define a POCO with any object structure that suits your needs, including nested objects, arrays, lists, and any data types.

If the default field mapping behavior does not meet your needs, you can specify custom behavior using serialization-related attributes. These attributes change the way that the driver serializes each property of your POCO. This section describes some of the common serialization-related attributes.

The driver serializes POCO properties to BSON fields with the same field name and capitalization. To store a property under a different name, use the [BsonElement()] attribute. The following code maps the YearBuilt property of the House class to the year_built field in the serialized BSON document:

public class House
public ObjectId Id { get; set; }
public int YearBuilt { get; set; }

Though it is common to use the Pascal case naming convention when defining C# classes, using the [BsonElement()] attribute allows you to select a different or custom naming convention in your MongoDB collection.


Set Custom Field Name Convention

If you want to serialize every property with a custom field name, you can define a ConventionPack instead of using the [BsonElement()] attribute. For example, if you define your class using the Pascal case naming convention, you can use the following code to use camel case field names in the serialized document:

var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);

To serialize a C# property to a specific BSON type, use the [BsonRepresentation()] attribute. This works only if the C# primitive type is convertible to the BSON type you specify. In the following code sample, the YearBuilt property, defined as a char in C#, is serialized as a BSON Int32 type:

public class House
public ObjectId Id { get; set; }
public char YearBuilt { get; set; }

For more information on valid type conversions, see the C# Conversions Specification.

The driver serializes properties to BSON fields in the order they are specified in the POCO. To store properties in a custom order to match an existing schema, you can specify the Order named parameter in the [BsonElement()] attribute. In the following code sample, the driver stores the YearBuilt property after the Style property:

public class House
public ObjectId Id { get; set; }
[BsonElement(Order = 2)]
public int YearBuilt { get; set; }
[BsonElement(Order = 1)]
public string Style { get; set; }

If any properties don't have an explicit Order, the driver will serialize them in the default order after those that do.

By default, the driver maps any public property named Id, id, or _id to the BSON _id field. To explicitly select the property to map to the _id field, use the [BsonId()] attribute. The following code sample maps the Identifier property to the _id field:

public class House
public string Identifier { get; set; }


Multiple Id Fields

If you identify more than one property as the _id field using the [BsonId()] attribute, the driver throws a DuplicateBsonMemberMapAttributeException. If you specify the same database field more than once (for example, if your POCO includes properties named Id and _id), the driver throws a BsonSerializationException.

By default, the driver serializes undefined properties to fields with null values. To ignore undefined properties during serialization, use the [BsonIgnore()] attribute. The following code shows how you can prevent the driver from serializing the YearBuilt property if it is undefined:

public class House
public ObjectId Id { get; set; }
public int YearBuilt { get; set; }
public string Style { get; set; }

The following example shows how to insert a Clothing document with custom field mapping specifications into MongoDB.

The following code defines the Clothing class with these serialization-related attributes:

  • [BsonElement()], which specifies custom field names in the camel case naming convention

  • [BsonRepresentation()], which specifies serialization of the Price field as a BSON Double type

public class Clothing
public ObjectId Id { get; set; }
public string Name { get; set; }
public bool InStock { get; set; }
public decimal Price { get; set; }
public List<string> ColorSelection { get; set; }

The following code instantiates a Clothing object and inserts the document into a collection:

var doc = new Clothing
Name = "Denim Jacket",
InStock = false,
Price = 32.99m,
ColorSelection = new List<string> { "dark wash", "light wash" }

The BSON representation of the inserted document looks like this:

"_id": ObjectId("..."),
"name": "Denim Jacket",
"inStock": false,
"price": 32.99,
"colorSelection": [ "dark wash", "light wash" ]

For a full list of serialization-related attributes, see the Serialization.Attributes API documentation.

For additional read and write operation examples using POCOs, see the Usage Examples or the CRUD Fundamentals Pages.

To learn more about how the driver maps BSON documents to POCOs, see Class Mapping.

To learn more about any of the methods or types discussed in this guide, see the following API documentation:

←  Work with BSONGUID Serialization →
Share Feedback
© 2023 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.