mongoDb开发学习

http://www.cnblogs.com/xumingxiang/archive/2012/04/08/2437468.html#title1

-------------------------------------------------------------------

csharp操作mongodb的winfom示例

private MongoDatabase db;
private void button1_Click(object sender, EventArgs e)
{
//链接获得数据库
const string strconn = "mongodb://127.0.0.1:27017";
const string dbName = "cnblogs";
MongoClient client=new MongoClient(strconn);
MongoServer server = client.GetServer();
db = server.GetDatabase(dbName);
DatabaseStatsResult dr = db.GetStats();
if (dr.Ok)
{
MessageBox.Show("链接成功!");
}
}

private void button2_Click(object sender, EventArgs e)
{
Users users=new Users();
users.Name = "黄";
users.Sex = "男";
MongoCollection col = db.GetCollection("Users");
WriteConcernResult wr= col.Insert<Users>(users);
if (wr.Ok)
{
MessageBox.Show("插入成功!");
}
users = col.FindOneAs<Users>();
MessageBox.Show(users.Name + users.Age + users.Sex);
}

private void button3_Click(object sender, EventArgs e)
{
MongoCollection col= db.GetCollection("Users");
var query = new QueryDocument {{"Name","黄"}};
var update = new UpdateDocument {{"$set", new QueryDocument {{"Sex", "女"}}}};
WriteConcernResult wr= col.Update(query, update);
if (wr.Ok)
{
MessageBox.Show("更新成功!");
}
Users users = col.FindOneAs<Users>();
MessageBox.Show(users.Name + users.Age + users.Sex);
}

private void button4_Click(object sender, EventArgs e)
{
MongoCollection col= db.GetCollection("Users");
var query = new QueryDocument {{"Name", "黄"}};
WriteConcernResult wr= col.Remove(query);
if (wr.Ok)
{
MessageBox.Show("删除成功!");
}
Users users = col.FindOneAs<Users>();
if(users!=null)
MessageBox.Show(users.Name + users.Age + users.Sex);
}

private void button5_Click(object sender, EventArgs e)
{
MongoCollection col = db.GetCollection("Users");
//var query = new QueryDocument {{"Name", "小黄"}};
var query = Query.EQ("Name", "小黄");
query = Query.GT("Age", 25);
query = Query.LT("Age", 25);

query= Query.In("Age", new List<BsonInt32> {25, 26, 27});
query = Query.NotIn("Age", new List<BsonInt32> {25, 26, 27});

query= Query.And(Query.GT("Age", 20), Query.LT("Sex", "男"));
query= Query.Or(Query.GT("Age", 20), Query.LT("Sex", "男"));

query = Query.Exists("BirthDay");
query= Query.NotExists("BirthDay");
query= Query.Mod("Age", 10, 1);

var sort = SortBy.Ascending("Age");
sort = SortBy.Descending("Age");

var tQuery = Query<Users>.In(x => x.Age, new List<BsonInt32> { 25, 26, 27 });
var tSort= SortBy<Users>.Descending(x => x.Age);

var result1 = col.FindAllAs<Users>().ToList();
var result2 = col.FindOneAs<Users>();
var result3 = col.FindAs<Users>(query).SetSortOrder(sort).Distinct().Skip(20).Take(10).ToList();

}

你可能感兴趣的:(mongodb)