Using MongoDB in C#

獨木發表於2013-12-29

In order to use MongoDB in C#, you can import MongoDB C# Driver to your project. It's best to create some dummy base class for convenience.

 

1 using MongoDB.Driver;
2 using MongoDB.Driver.Builders;

 

Base class for data objects. Each record must have a Id.

1 using MongoDB.Bson;
2 using MongoDB.Bson.Serialization.Attributes;

 

 1     public interface IMongoEntity
 2     {
 3         ObjectId Id { get; set; }
 4     }
 5 
 6     public class MongoEntity : IMongoEntity
 7     {
 8         [BsonIgnoreIfDefault]
 9         [BsonId]
10         public ObjectId Id { get; set; }
11     }

 

Then a real model class.

 1 [BsonIgnoreExtraElements]
 2     class MyObject : MongoEntity
 3     {
 4         [BsonElement("symbol")]
 5         public string Symbol
 6         {
 7             get;
 8             set;
 9         }
10    }

 

Connect to local MongoDB server and push some data.

 1 var connectionString = "mongodb://localhost";
 2 var client = new MongoClient(connectionString);
 3 
 4 var server = client.GetServer();
 5 
 6 var database = server.GetDatabase("tutorial"); // "test" is the name of the database
 7 
 8 // "entities" is the name of the collection
 9 var collection = database.GetCollection<MongoEntity>("test");
10 
11 MongoEntity newEntity = new MyObject {
12         Symbol = "Tom"
13 };
14 
15 Upsert(collection, newEntity);

 

相關文章