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);
  • 相关阅读:
    备战-Java 并发
    备战-Java 容器
    备战-Java 基础
    算法-链表
    2021-常见问题收集整理-1
    算法-双指针
    HTTP 下载文件的一些记录
    语义化版本 2.0.0
    勒索病毒典型传播途径与预防建议
    看杨院士如何解读——北斗与综合PNT体系
  • 原文地址:https://www.cnblogs.com/huys03/p/3476594.html
Copyright © 2011-2022 走看看