Last active
December 20, 2015 05:09
-
-
Save leoncamel/6076222 to your computer and use it in GitHub Desktop.
Serialization in C# driver of MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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