一、下载驱动
MongoDB.Driver;MongoDB.Bson;两个驱动
二、连接数据库
string conn = "mongodb://localhost";
string database = "personName";
string collection = "Student";
MongoServer mongodb = MongoServer.Create(conn); // 连接数据库
MongoDatabase mongoDataBase = mongodb.GetDatabase(database); // 选择数据库名
MongoCollection mongoCollection = mongoDataBase.GetCollection(collection); // 选择集合,相当于表
mongodb.Connect();
三、新建实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
namespace CodeFactory.mongo
{
class PersonEntity
{
public ObjectId _id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
}
四、插入数据
PersonEntity he = new PersonEntity();
he.name = "Jack";
he.age = 19;
mongoCollection.Insert(he);
五、条件查询
string msg = string.Empty;
// 单条件查询全部数据
MongoCursor<PersonEntity> mc = mongoCollection.FindAllAs<PersonEntity>();
foreach (PersonEntity person in mc)
{
msg += "_id:" + person._id.ToString() + " name:" + person.name.ToString() + " age:" + person.age.ToString() + "\n";
}
//单条件查找返回一条数据
var msg1 = "";
QueryDocument query1 = new QueryDocument("name", "linda");
PersonEntity mc1 = mongoCollection.FindOneAs<PersonEntity>(query1);
msg1 = mc1.name + "&" + mc1.age;
var msg2 = "";
// 多条件查询
QueryDocument query2 = new QueryDocument
{
{"name", "Nancy"},
{"age", 30}
};
mc = mongoCollection.FindAs<PersonEntity>(query2);
foreach (PersonEntity person in mc)
{
msg2 += "_id:" + person._id.ToString() + " name:" + person.name.ToString() + " age:" + person.age.ToString() + "\n";
}
六、根据条件更新数据
// 根据条件更新一个值
var update = new UpdateDocument {
{ "$set", new BsonDocument("age", 30) }
};
mongoCollection.Update(query2, update);//query为五中的查询条件
// 根据条件更新多个值
var update1 = new UpdateDocument {
{ "$set", new BsonDocument{
{"name", "jack7"},
{"age", 31}
} }
};
mongoCollection.Update(query2, update1);
七、根据时间区间查询数据
// 条件查询数据
QueryDocument query = new QueryDocument();
BsonDocument b = new BsonDocument();
b.Add("$gt", Convert.ToDateTime(startTime.ToString()).ToString("u"));
b.Add("$lt", Convert.ToDateTime(endTime.ToString()).ToString("u"));
query.Add("times", b);
MongoCursor<HisData> mc = mongoCollection.FindAs<HisData>(query);
int i = 0;
foreach (HisData data in mc)
{
//data
}