关于对象与BsonDocument的映射,参见官方文档:http://mongodb.github.io/mongo-csharp-driver/2.2/reference/bson/mapping/
比使用关系型数据库确实是方便太多了。
需求:
1)基础类型作为类的属性;
2)后期需要对类进行动态配置扩展,所以需要能添加自定义扩展属性;
3)需要有关键字等不定长的标记;
解决方法:
1)做属性名映射;
2)添加Hashtable或者Dictionary用来存放扩展的属性;
3)添加IList存放各种扩展的tag;
实体类的定义如下:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.IdGenerators;
namespace testMongo
{
[BsonDiscriminator("user")]
public class User
{
//[BsonIgnore]
[BsonId(IdGenerator = typeof(MyGenerator))]
public long ID { get; set; }
[BsonElement("num")]
public long Num { get; set; }
[BsonElement("username")]
public string Name { get; set; }
[BsonElement("pwd")]
public string Pwd { get; set; }
[BsonElement("chu")]
public string Chu { get; set; }
[BsonElement("createTime")]
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime Created { get; set; }
[BsonElement("tags")]
public List<string> Tags { get; set; }
[BsonDictionaryOptions]
public IDictionary<string, string> table { get; set; }
public Object GetClientProperty(String key)
{
if (table != null)
return table[key];
return null;
}
public void SetClientPropery(String key, String o)
{
if (table == null)
table = new Dictionary<string, string>();
table.Add(key, o);
}
}
public class MyGenerator : IIdGenerator
{
// 雪花算法,自己百度了一个
private static readonly IdWorker worker = new IdWorker(1);
public static long getNextId()
{
return worker.nextId();
}
public object GenerateId(object container, object document)
{
return worker.nextId();
}
public bool IsEmpty(object id)
{
return id == null || Convert.ToInt64(id) == 0;
}
}
}
封装一个简单访问类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
namespace testMongo
{
public class MongoHelper
{
// mongod --dbpath=D:\mongodb\db --logpath=D:\mongodb\log.txt --install --serviceName "MongoDB" --auth
public static string FormatConnStr(string ip, string port, string user, string pwd, string dbname)
{
// "mongodb://sa:123@127.0.0.1:27017/db";
String connectionString = String.Format(@"mongodb://{0}:{1}@{2}:{3}/{4}",
user,
pwd,
ip,
port,
dbname);
return connectionString;
}
static MongoClient client = null;
static IMongoDatabase db = null;
public static IMongoDatabase getDb(string conn, string dbName)
{
//连接服务端
MongoHelper.client = new MongoClient(conn);
//获取指定数据库
MongoHelper.db = client.GetDatabase(dbName);
return MongoHelper.db;
}
public static IList<User> GetAllUsers()
{
FilterDefinitionBuilder<User> builderFilter1 = Builders<User>.Filter;
IMongoCollection<User> tableUser = db.GetCollection<User>("Members");
if (tableUser == null)
return null;
var retUsers = tableUser.Find<User>(builderFilter1.Empty).ToList<User>();
return (IList<User>)retUsers;
}
public static IList<User> FindUsersByNum(long num)
{
//创建约束生成器
FilterDefinitionBuilder<User> builderFilter = Builders<User>.Filter;
IMongoCollection<User> tableUser = db.GetCollection<User>("Members");
if (tableUser == null)
return null;
//约束条件
FilterDefinition<User> filter = builderFilter.Eq("num", num);
var retUsers = tableUser.Find<User>(filter).ToList<User>();
return (IList<User>)retUsers;
}
// 插入一条数据
public static bool InsertOneUser(ref User user)
{
try
{
IMongoCollection<User> tableUser = db.GetCollection<User>("Members");
if (tableUser == null)
{
db.CreateCollection("Members");
tableUser = db.GetCollection<User>("Members");
if (tableUser == null)
return false;
}
tableUser.InsertOne(user);
}
catch(Exception ex)
{
errorInfo = ex.Message;
}
return true;
}
public static bool InsertUsers(ref List<User> users)
{
try
{
IMongoCollection<User> tableUser = db.GetCollection<User>("Members");
if (tableUser == null)
{
db.CreateCollection("Members");
tableUser = db.GetCollection<User>("Members");
if (tableUser == null)
return false;
}
tableUser.InsertMany(users);
}
catch (Exception ex)
{
errorInfo = ex.Message;
}
return true;
}
public static String errorInfo;
private static DateTime beforeDT;
private static DateTime afterDT;
TimeSpan ts = afterDT.Subtract(beforeDT);
public static void BeginTime()
{
beforeDT = System.DateTime.Now;
}
public static double EndTime()
{
afterDT = System.DateTime.Now;
TimeSpan ts = afterDT.Subtract(beforeDT);
return ts.TotalMilliseconds;
}
}
}
执行一个测试:
string conn = MongoHelper.FormatConnStr("127.0.0.1", "27017", "userDevice", "123456", "device");
IMongoDatabase db = MongoHelper.getDb(conn, "device");
List<User> listUsers = new List<User>();
for (int i =0; i<10000; i++)
{
// 测试创建
var user = new User();
user.Num = i;
user.Name = "robin" + i.ToString();
user.Pwd = "123456";
user.Chu = "二处";
user.Created = DateTime.Now;
// user.ID = MyGenerator.getNextId();
user.SetClientPropery("sex", "男");
user.SetClientPropery("birth", "19810101");
user.Tags = new List<string>();
user.Tags.Add("已处理");
user.Tags.Add("注销");
listUsers.Add(user);
}
// 测试插入新能
MongoHelper.BeginTime();
MongoHelper.InsertUsers(ref listUsers);
double ms = MongoHelper.EndTime();
String info = String.Format("DateTime costed for Shuffle function is: {0}ms", ms);
MongoHelper.BeginTime();
IList<User> retList = MongoHelper.FindUsersByNum(15);
ms = MongoHelper.EndTime();
// 测试
textBox1.Text = info;
结果:
批量插入10000条数据,需要400ms,
查询20000条,找到2条,需要40ms