2012年3月6日 星期二

Using MongoDB via Official C# Driver

My document format (for example)
{
    ID : "...",
    Message : "..."
};

C# reference
MongoDB.Bson.dll and MongoDB.Driver.dll

C# namespace
You also will likely want to add the following using statements to your source files:
using MongoDB.Bson;
using MongoDB.Driver;
You might need to add some of the following using statements if you are using some of the optional parts of the C# Driver:
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization.Options;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Wrappers;

Connect to Mongodb
MongoServer server = MongoServer.Create(connString);
MongoDatabase database = server.GetDatabase("database");

Query by ID
var messages = database.GetCollection<BsonDocument>("messages");

QueryDocument query = new QueryDocument("ID", ID);
BsonDocument doc = messages.FindOne(query);

// Do not cast to System.String
Console.WriteLine((string)doc["Message"]);

Insert
var messages = database.GetCollection<BsonDocument>("messages");

BsonDocument doc = new BsonDocument
{
    { "ID", "..." },
    { "Message", "..." }
};
messages.Insert(doc);

Delete by ID
var messages = database.GetCollection<BsonDocument>("messages");

QueryComplete query = Query.EQ("ID", "...");
messages.Remove(query);

Reference: http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial

沒有留言:

張貼留言