C#操作MongoDB資料庫並獲取資料方法
阿新 • • 發佈:2018-12-24
本文利用MongoDB官方釋出的C#驅動,封閉了對MongoDB資料庫的增刪改查訪問方法。
1、引用MongoDB for C# Driver
從網上下載C#訪問MongoDB的驅動,得到兩個DLL:
- MongoDB.Driver.dll
- MongoDB.Bson.dll
將它們引用到專案中。
2、編寫實體類
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MongoDbTest{ public class Shiti { public string a { get; set; } public string b { get; set; } } }
3、編寫資料庫訪問幫助類
編寫MongoDB訪問幫助類MongoDbHelper:
namespace MongoDbTest { public class MongoDbHepler { private MongoClient client; public IMongoDatabase database; protected IMongoCollection<BsonDocument> collection; private List<Shiti> lstvalue; public List<Shiti> Get_Data() { List<Shiti> lst = new List<Shiti>(); client = new MongoClient("mongodb://192.168.1.1:30001"); database=client.GetDatabase("Database"); collection=database.GetCollection<BsonDocument>("collection"); var filter = Builders<BsonDocument>.Sort.Descending("日期"); var documents = collection.Find(_ => true).Sort(filter).Limit(50).ToListAsync().Result; if (documents.Count > 0) { for (int i = 0; i < documents.Count; i++) { var document = documents[i]; String a = document.GetElement("a") + ""; ; String b = document.GetElement("b") + ""; ; Shiti shiti = new Shiti (); shiti .a = a; shiti .b = b ; lst.Add(shiti ); lstvalue = lst.ToList(); } } return lstvalue; } } }