您的位置:首页 > 数据库 > Mongodb

【MongoDB初识】-结合C#简单使用,驱动2.x

2015-11-02 15:51 961 查看
public static Students GetEntityByName(string conStr, string userName = "bj")
{
Students s = new Students();
MongoClient client = new MongoClient(conStr);
var db = client.GetDatabase("test");
var collection = db.GetCollection<Students>("students");
var query = Builders<Students>.Filter.Eq("name", "hhe");
s = collection.Find(query).FirstAsync().Result;
return s;
}
public static List<Students> GetEntityList(string conStr)
{
List<Students> list = new List<Students>();
MongoClient client = new MongoClient(conStr);
var db = client.GetDatabase("test");
var collection = db.GetCollection<Students>("students");
list = collection.Find(a => a.age > 12).SortBy(a => a.age).ToListAsync().Result;
return list;
}

public static bool UpdateEntityByName(string conStr, string userName = "bj")
{
bool s = false;
MongoClient client = new MongoClient(conStr);
var db = client.GetDatabase("test");
var collection = db.GetCollection<Students>("students");
var query = Builders<Students>.Filter.Eq("name", "hhe");
var update = Builders<Students>.Update.Set(a => a.name, "hhee");
//Builders<Student>.Update.AddToSetEach(s => s.CoursesList, courseList)
var ss = collection.UpdateOneAsync(query, update).Result;
if (ss.IsAcknowledged)
{
s = true;
}
return s;
}
public static async Task InsertEntity(string conStr)
{
Students s = new Students() { name = "www1", classid = 6, age = 26 };
MongoClient client = new MongoClient(conStr);
var db = client.GetDatabase("test");
var collection = db.GetCollection<Students>("students");
await collection.InsertOneAsync(s);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: