Skip to content

Instantly share code, notes, and snippets.

@leoncamel

leoncamel/gist:6076222

Last active Dec 20, 2015
Embed
What would you like to do?
Serialization in C# driver of MongoDB
using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Options;
using MongoDB.Driver;
namespace TestMongoDot
{
class MyEntity
{
public ObjectId Id { get; set; }
public string Name { get; set; }
// NOTE :
// Ensure dictionary is serilize as Document, if you
// want query like "something.something".
// Or it will *automatically" serilize as array, if your
// key contains a "." or "$"
//
// Reference : https://github.com/mongodb/mongo-csharp-driver/blob/master/MongoDB.DriverUnitTests/Linq/SelectDictionaryTests.cs
//
[BsonDictionaryOptions(DictionaryRepresentation.Document)]
public Dictionary<string, string> mydict;
}
class Program
{
static void Main(string[] args)
{
var connStr = "mongodb://localhost";
var mgClient = new MongoClient(connStr);
var mgServer = mgClient.GetServer();
var db = mgServer.GetDatabase("test");
var coll = db.GetCollection<MyEntity>("myDotEntity");
var ent = new MyEntity {Name = "Jacky"};
var dict = new Dictionary<string, string>();
dict["hello.haha"] = "world";
ent.mydict = dict;
coll.Insert(ent);
var id = ent.Id;
Console.WriteLine(id);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.