Skip to content

Instantly share code, notes, and snippets.

@ruxo
Created August 22, 2020 08:37
Show Gist options
  • Select an option

  • Save ruxo/255a92ff2abea67f0ce941c5365dcf3a to your computer and use it in GitHub Desktop.

Select an option

Save ruxo/255a92ff2abea67f0ce941c5365dcf3a to your computer and use it in GitHub Desktop.
Sample of C# MongoDB with Immutable classes
// reference MongoDB.Driver 2.11.0
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
void Main()
{
var client = new MongoClient("mongodb://connection");
var collection = client.GetDatabase("test").GetCollection<Test>("test");
collection.InsertOne(new Test("key", 123, new TestX(123.45m)));
collection.Find(t => t.Key == "key").Single().Dump();
}
public sealed class Test {
[BsonId]
public string Key {get;}
public long Offset {get;}
public TestX Data {get;}
public Test(string Key, long Offset, TestX Data) {
this.Key = Key;
this.Offset = Offset;
this.Data = Data;
}
}
public sealed class TestX {
public decimal Value { get; }
public TestX(decimal Value) { this.Value = Value; }
}
@ruxo
Copy link
Copy Markdown
Author

ruxo commented Aug 22, 2020

Note, MongoDB only serializes properties, no fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment