Lesson 1: Working with MongoDB Documents in C# / Learn
Working with MongoDB Documents in C#
Review the following code, which demonstrates how to represent a document in C#.
BsonDocument
Use MongoDB.Bson to represent a document with BsonDocument. Here's an example:
using MongoDB.Bson;
var document = new BsonDocument
{
{ "account_id", "MDB829001337" },
{ "account_holder", "Linus Torvalds" },
{ "account_type", "checking" },
{ "balance", 50352434 }
};
C# Class (POCOs)
Each public property maps to a field in the BSON document.
- The
BsonIdattribute specifies a field that must always be unique. - The
BsonRepresentationattribute maps a C# type to a specific BSON type. - The
BsonElementattribute maps to the BSON field name.
Here's an example:
internal class Account
{
[BsonId]
[BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("account_id")]
public string AccountId { get; set; }
[BsonElement("account_holder")]
public string AccountHolder { get; set; }
[BsonElement("account_type")]
public string AccountType { get; set; }
[BsonRepresentation(BsonType.Decimal128)]
[BsonElement("balance")]
public decimal Balance { get; set; }
[BsonElement("transfers_complete")]
public string[] TransfersCompleted { get; set; }
}