Skip to content

Instantly share code, notes, and snippets.

@leoncamel
Last active December 20, 2015 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leoncamel/6076222 to your computer and use it in GitHub Desktop.
Save leoncamel/6076222 to your computer and use it in GitHub Desktop.
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