Mongodb c#增删改查

时间:2022-08-26 01:54:52

写在前面

最近项目需要,就研究了下mongodb,也是为了快速上手,就自己弄了一个简单的例子,这里记录一下。

Mongodb

传统的关系数据库一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。MongoDB对于关系型数据库里的表,但是集合中没有列、行和关系概念,这体现了模式*的特点。

那么在c#如何使用呢?下面看个例子,你会发现上手非常简单。

要操作数据库,首先考虑的就是连接字符串的问题,因为这就相当于你从那儿拿数据,先要有路子才行。

MongoDB 标准连接字符串

mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]

mongodb:// 是连接字串必须的前缀字串。

username:password@ 可选项,连接到数据库后会尝试验证登陆。

host1 必须的指定至少一个host。

:portX 可选项,默认连接到27017

/database 如果指定username:password@,连接并验证登陆指定数据库。若不指定,默认打开admin数据库。

?options 是连接选项。如果不使用/database,则前面需要加上/。所有连接选项都是键值对name=value,键值对之间通过&或;(分号)隔开。

关于options可参考官网的东西。

说这些不如先上个例子,先上手实践一下。

          /// <summary>
/// 连接字符串
/// </summary>
private static readonly string _connectionString = "mongodb://sa:sa@192.168.1.105:27017/Test_mongo";
private static readonly string _dbName = "Test_mongo";

在c#中使用Mongodb需要引入如下的dll
采用Nuget进行安装就可以了。

Mongodb c#增删改查

增删改查的代码如下:

        /// <summary>
/// 新增
/// </summary>
/// <param name="customer"></param>
private static void Insert(Customer customer)
{
//创建mogodb对象
using (Mongo mongo = new Mongo(_connectionString))
{
//连接mongodb
mongo.Connect();
//获得要操作的数据库
var db = mongo.GetDatabase(_dbName);
//获取要操作的Collection
var collection = db.GetCollection<Customer>();
collection.Insert(customer);
}
}
/// <summary>
/// 批量添加
/// </summary>
/// <param name="lstCustomer"></param>
private static void InsertList(List<Customer> lstCustomer)
{
using (Mongo mongo = new Mongo(_connectionString))
{
mongo.Connect();
var db = mongo.GetDatabase(_dbName);
var collection = db.GetCollection<Customer>();
collection.Insert(lstCustomer);
}
}
/// <summary>
/// 更新
/// </summary>
/// <param name="customer"></param>
private static void Update(Customer customer)
{
using (Mongo mongo = new Mongo(_connectionString))
{
mongo.Connect();
var db = mongo.GetDatabase(_dbName);
var collection = db.GetCollection<Customer>();
//更新对象
collection.Update(customer, (x => x.CustomerID == customer.CustomerID));
}
}
/// <summary>
/// 获取所有的customer
/// </summary>
/// <returns></returns>
private static IList<Customer> GetList()
{
using (Mongo mongo = new Mongo(_connectionString))
{
mongo.Connect();
var db = mongo.GetDatabase(_dbName);
var collection = db.GetCollection<Customer>();
ICursor<Customer> mogoCollection = collection.FindAll(); return mogoCollection.Documents.ToList();
}
}
/// <summary>
/// 根据id获取单个对象
/// </summary>
/// <param name="customerId"></param>
/// <returns></returns>
private static Customer GetById(string customerId)
{
using (Mongo mongo = new Mongo(_connectionString))
{
mongo.Connect();
var db = mongo.GetDatabase(_dbName);
var collection = db.GetCollection<Customer>();
return collection.FindOne(x => x.CustomerID == customerId);
}
}
}
[Serializable]
class Customer
{
[MongoId]
public string CustomerID { set; get; }
public string CustomerName { set; get; }
public string ContactName { set; get; }
public string Address { set; get; }
public string PostalCode { set; get; }
public string Tel { set; get; }
}

测试

 static void Main(string[] args)
{
#region 批量插入
//List<Customer> list = new List<Customer>();
//for (int i = 0; i < 100; i++)
//{
// Customer customer = new Customer()
// {
// CustomerID = Guid.NewGuid().ToString(),
// Address = "北京" + i.ToString(),
// CustomerName = "wolfy" + i.ToString(),
// Tel = "123" + i.ToString(),
// PostalCode = "221212" + i.ToString(),
// ContactName = "wolfy" + i.ToString()
// };
// list.Add(customer);
//}
//InsertList(list);
#endregion
#region 更新
//更新需要先将该对象查询出,然后更新修改的值,不然其他的值为null
//Update(new Customer() { CustomerID = "08dca525-fb6d-4984-a55f-53723a6ce39c", ContactName = "wolfy22222" });
#endregion
#region 查询单个对象和集合
//Customer customer = GetById("8211501b-4341-4acb-b2fa-d6a714765443");
//Console.WriteLine(new JavaScriptSerializer().Serialize(customer));
List<Customer> customers = GetList().ToList();
Console.WriteLine(new JavaScriptSerializer().Serialize(customers));
#endregion
Console.Read();
}

总结

到这里就结束了,这里弄了一个简单例子,算是快速上手的例子。