C# Asp.net中简单操作MongoDB数据库

xiaoxiao2021-02-28  15

需要引用MongoDB.Driver.dll、MongoDB.Driver.core.dll、MongoDB.Bson.dll三个dll。

同时如果项目报“错误:缺少 System.Runtime.InteropServices.RuntimeInformation.dll version = 4.0.0 ”错误的话,

需要引用System.Runtime.InteropServices.RuntimeInformation.dll ,编译到bin里。

1、数据库连接:

using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MongoDBDemo {     public class MongoDb     {         //方式一         private static readonly string connStr = "mongodb://myAdmin:123456@localhost";         private static readonly string dbName = "myTest";         //方式二(myTestAdmin用户只可访问数据库myTest)         //private static readonly string connStr = "mongodb://myTestAdmin:123456@localhost/myTest";                  private static IMongoDatabase db = null;         private static readonly object lockHelper = new object();         private MongoDb() { }         public static IMongoDatabase GetMongoDb()         {             if (db == null)             {                 lock (lockHelper)                 {                     if (db == null)                     {                         //方式一                         var client = new MongoClient(connStr);                         db = client.GetDatabase(dbName);                         //方式二(myTestAdmin用户只可访问数据库myTest)                         //var url = new MongoUrl(connStr);                         //MongoClientSettings mcs = MongoClientSettings.FromUrl(url);                         //mcs.MaxConnectionLifeTime = TimeSpan.FromMilliseconds(1000);                         //var client = new MongoClient(mcs);                         //db = client.GetDatabase(url.DatabaseName);                     }                 }             }             return db;         }     } }

2、自定义类(model类):

public class BaseEntity { //字段映射,告诉mongodb这个字段在数据库中对应_id [BsonId] //告诉mongodb这个字段在数据库中的类型是ObjectId [BsonRepresentation(BsonType.ObjectId)] public string _id { get; set; } } public class IPInfo : BaseEntity { public string ip { get; set; } public string ipAddress { get; set; } public string addTime { get; set; } } public class IPDetails : BaseEntity { /// <summary> /// 主表id /// </summary> [BsonRepresentation(BsonType.ObjectId)] public string parentId { get; set; } public string ipAddress { get; set; } public string ipNetwork { get; set; } public string ipBrowser { get; set; } public string addTime { get; set; } }

3、业务逻辑:

using MongoDB.Bson; using MongoDB.Driver; using MongoDBDemo.model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace MongoDBDemo.bll { /// <summary> /// ip信息主表 /// </summary> public class IPInfoFactory { /// <summary> /// 集合(表)名称 /// </summary> private static readonly string CollectionName = "IPInfo"; //ip子表名称 private static readonly string ChildCollectionName = "IPDetail"; private static IMongoDatabase db = MongoDb.GetMongoDb(); public static List<IPInfo> GetAllList() { try { var collection = db.GetCollection<IPInfo>(CollectionName); List<IPInfo> list = collection.Find(new BsonDocument()).ToList(); return list; } catch (Exception ex) { return null; } } /// <summary> /// 获取 /// </summary> /// <param name="id"></param> /// <returns></returns> public static IPInfo Get(string id) { try { var IPInfoCollection = db.GetCollection<IPInfo>(CollectionName); var filter = Builders<IPInfo>.Filter.Eq("_id", id); var item = IPInfoCollection.Find(filter).FirstOrDefault(); return item; } catch (Exception ex) { return null; } } /// <summary> /// 插入主表 /// </summary> /// <returns></returns> public static bool Add(string ip, string ipAddress) { try { var IPInfoCollection = db.GetCollection<IPInfo>(CollectionName); IPInfo ipInfo = new IPInfo(); ipInfo.ip = ip; ipInfo.ipAddress = ipAddress; ipInfo.addTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); IPInfoCollection.InsertOne(ipInfo); return true; } catch (Exception ex) { return false; } } /// <summary> /// 修改 /// </summary> /// <param name="id"></param> /// <returns></returns> public static bool Update(IPInfo model) { try { var IPInfoCollection = db.GetCollection<IPInfo>(CollectionName); var filter = Builders<IPInfo>.Filter.Eq("_id", model._id); IPInfoCollection.ReplaceOne(filter, model); return true; } catch (Exception ex) { return false; } } /// <summary> /// 删除 /// </summary> /// <param name="id"></param> /// <returns></returns> public static bool Delete(string id) { try { var IPInfoCollection = db.GetCollection<IPInfo>(CollectionName); var filter = Builders<IPInfo>.Filter.Eq("_id", id); IPInfoCollection.DeleteOne(filter); return true; } catch (Exception ex) { return false; } } /// <summary> /// 插入主表、子表: /// 主表:有则不插入,无则插入; /// 子表:一条数据都没有,则插入,已经存在数据,判断是否存在一条相同数据,存在则不插入,不存在则插入。 /// </summary> /// <returns></returns> public static bool AddIPInfoAndDetail(string ip, string ipAddress, string ipNetwork, string ipBrowser) { try { var IPInfoCollection = db.GetCollection<IPInfo>(CollectionName); var IPDetailCollection = db.GetCollection<IPDetails>(ChildCollectionName); //判断主表是否已经存在 var pFilter = Builders<IPInfo>.Filter.Eq("ip", ip); var parentItem = IPInfoCollection.Find(pFilter).FirstOrDefault(); if (parentItem == null) { //插入主表 IPInfo ipInfo = new IPInfo(); ipInfo.ip = ip; ipInfo.ipAddress = ipAddress; ipInfo.addTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); IPInfoCollection.InsertOne(ipInfo); //插入子表 string parent_id = string.Empty; //刚插入的主表 var parentItemNew = IPInfoCollection.Find(pFilter).FirstOrDefault(); if (parentItemNew != null) { parent_id = parentItemNew._id; AddChild(parent_id, ipAddress, ipNetwork, ipBrowser); } } else { string parent_id = parentItem._id; var childFilter1 = Builders<IPDetails>.Filter.Eq("parentId", parent_id); var childItem = IPDetailCollection.Find(childFilter1).FirstOrDefault(); if (childItem == null) { AddChild(parent_id, ipAddress, ipNetwork, ipBrowser); } else { //如果没有类似的数据,则插入 var filterBuilder = Builders<IPDetails>.Filter; var childFilter2 = filterBuilder.Eq("parentId", parent_id) & filterBuilder.Regex("ipNetwork", new BsonRegularExpression(new Regex(ipNetwork))) & filterBuilder.Regex("ipBrowser", new BsonRegularExpression(new Regex(ipBrowser))); var childItem2 = IPDetailCollection.Find(childFilter2).FirstOrDefault(); if (childItem2 == null) { AddChild(parent_id, ipAddress, ipNetwork, ipBrowser); } } } return true; } catch (Exception ex) { return false; } } /// <summary> /// 插入子表 /// </summary> /// <returns></returns> public static bool AddChild(string parentId, string ipAddress, string ipNetwork, string ipBrowser) { try { var IPDetailCollection = db.GetCollection<IPDetails>(ChildCollectionName); IPDetails ipDetails = new IPDetails(); ipDetails.parentId = parentId; ipDetails.addTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); ipDetails.ipAddress = ipAddress; ipDetails.ipNetwork = ipNetwork; ipDetails.ipBrowser = ipBrowser; IPDetailCollection.InsertOne(ipDetails); return true; } catch (Exception ex) { return false; } } } }

4、增删改查操作:

class Program { static void Main(string[] args) { try { //插入 //var addResult1 = IPInfoFactory.AddIPInfoAndDetail("127.0.0.1", "中国上海", "华东电信", "360"); var addResult = IPInfoFactory.Add("127.0.0.1", "中国上海"); //查询 var list = IPInfoFactory.GetAllList(); Console.WriteLine(JsonConvert.SerializeObject(list)); //修改 var item = IPInfoFactory.Get("5b441a337c210a1cfc409558"); item.ipAddress = "SH"; var updateResult = IPInfoFactory.Update(item); //删除 var deleteResult = IPInfoFactory.Delete("5b447dd79be4bb134c70d9c4"); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine("错误:" + ex.Message); } finally { Console.ReadKey(); } } }

使用Robomongo工具可以看到mongodb数据库数据:

代码下载:https://download.csdn.net/download/coderk2014/10533230

转载请注明原文地址: https://www.6miu.com/read-2800305.html

最新回复(0)