mongodb 举例
using MongoDB.Bson;
using MongoDB.Driver;
using System;
namespace Project.MongoDB
{
class Program
{
static void Main(string[] args)
{
//数据库连接字符串
//const string connectionString = "mongodb://127.0.0.1:27017";
const string connectionString = "mongodb://10.153.44.125:27017";
//数据库
const string Database = "ck_test_db";
MongoClient client = new MongoClient(connectionString);
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase(Database);
MongoCollection collection = db.GetCollection("student");
//新增
//student stud_Add = new student() { name = "赵云", code = "2001", sex = "女", age = "23" };
//collection.Insert<student>(stud_Add);
//更新
//QueryDocument query_upd = new QueryDocument { { "name", "赵云" } };
//IMongoUpdate update = Update.Set("code", "4444");
//collection.Update(query_upd, update);
//删除
//QueryDocument query_del = new QueryDocument { { "name", "赵云" } };
// collection.Remove(query_del);
//查询
QueryDocument query_sel = new QueryDocument { { "name", "赵云" } };
var list = collection.FindAs<student>(query_sel);
foreach (student item in list)
{
Console.WriteLine("name:{0},code:{1}", item.name, item.code);
}
Console.Read();
}
public class student
{
public ObjectId _id; //BsonType.ObjectId 这个对应了 MongoDB.Bson.ObjectId
public string name { get; set; }
public string code { get; set; }
public string sex { get; set; }
public string age { get; set; }
/*_id 属性必须要有,否则在更新数据时会报错:“Element '_id' does not match any field or property of class”。*/
}
}
}