I found that a more explicit sample was missing. So here it is the C# version of the article.
The real question I'm trying to answer is : how to map a POCO to MongoDb.
using System;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
namespace mdbBacASable {
class Program {
static void Main(String[] args) {
try {
String connectionString =
"mongodb://localhost:27017";
MongoServer mdbServer =
MongoServer.Create(connectionString);
MongoDatabase mdbTest =
mdbServer.GetDatabase("test");
MongoCollection<BsonDocument> bsDocBooks =
mdbTest.GetCollection<BsonDocument>("books");
bsDocBooks.RemoveAll();
BsonDocument bsDocBook = new BsonDocument {
{ "Author", "Ernest Hemingway" },
{ "Title", "For Whom the Bell Tolls" }
};
bsDocBooks.Insert(bsDocBook);
BsonDocument[] batch = {
new BsonDocument {
{ "Author", "Kurt Vonnegut" },
{ "Title", "Cat's Cradle" }
},
new BsonDocument {
{ "Author", "Kurt Vonnegut" },
{ "Title", "Slaughterhouse-Five" }
}
};
bsDocBooks.InsertBatch(batch);
//-----------------------------------------------
BsonClassMap.RegisterClassMap<Book>(cm => {
cm.AutoMap();
cm.SetIdMember(cm.GetMemberMap(c => c.Id));
});
MongoCollection<Book> Books =
mdbTest.GetCollection<Book>("books");
Book oBook = new Book() {
Author = "JRR Tolkien",
Title = "Lord of the Ring" };
Books.Insert(oBook);
//----------------------------------------------
Book Book = Books.FindOne();
Console.WriteLine("{0} : {1}",
Book.Author, Book.Title);
Console.WriteLine("\r\n------------------------\r\n");
foreach ( Book b in Books.FindAll() ) {
Console.WriteLine("{0} : {1} : {2}",
b.Id, b.Author, b.Title);
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
public class Book {
public ObjectId Id { get; set; }
public String Author { get; set; }
public String Title { get; set; }
}
}