Using MongoDB in C#

时间:2022-01-20 06:35:34

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.

 using MongoDB.Driver;
using MongoDB.Driver.Builders;

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

 using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
     public interface IMongoEntity
{
ObjectId Id { get; set; }
} public class MongoEntity : IMongoEntity
{
[BsonIgnoreIfDefault]
[BsonId]
public ObjectId Id { get; set; }
}

Then a real model class.

 [BsonIgnoreExtraElements]
class MyObject : MongoEntity
{
[BsonElement("symbol")]
public string Symbol
{
get;
set;
}
}

Connect to local MongoDB server and push some data.

 var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString); var server = client.GetServer(); var database = server.GetDatabase("tutorial"); // "test" is the name of the database // "entities" is the name of the collection
var collection = database.GetCollection<MongoEntity>("test"); MongoEntity newEntity = new MyObject {
Symbol = "Tom"
}; Upsert(collection, newEntity);