zoukankan      html  css  js  c++  java
  • Using MongoDB in C#

    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);
  • 相关阅读:
    bzoj4196: [Noi2015]软件包管理器
    bzoj3992: [SDOI2015]序列统计
    bzoj 4178: A
    Spoj 8372 Triple Sums
    hdu contest day1 1007 Tricks Device
    hdu contest day1 1002 Assignment
    2018暑期生活指导第三周
    2018暑期生活指导第二周
    《大道至简》阅读笔记
    2018暑期生活指导第一周
  • 原文地址:https://www.cnblogs.com/huys03/p/3476594.html
Copyright © 2011-2022 走看看