MongoDB的文档结构描述数据关系 MongoDB学习笔记(四) 用MongoDB的文档结构描述数据关系
人气:0MongoDB的集合(collection)可以看做关系型数据库的表,文档对象(document)可以看做关系型数据库的一条记录。但两者并不完全对等。表的结构是固定的,MongoDB集合并没有这个约束;另外,存入集合的文档对象甚至可以嵌入子文档,或者“子集合”。他们最终都可以用类似于BJSON的格式描述。我们今天就来分析MongoDB这一特性带来的独特数据管理方式。我们还是以samus驱动为例来分析,samus驱动支持两种方式访问数据库,基本方式和linq方式,基本方式在上篇以介绍过,linq方式我不想单独讲解应用实例,这篇我会用两种方式来对比介绍。
一、包含子文档的集合操作
有这么一个应用场景,某网站提供会员登录的功能,用户需要注册账号才能享受会员服务,但是注册者可能会因为用户资料表单输入项过大而放弃填写,因此用户信息分为主要资料和详细资料两项,初次注册只需要填写主要资料就行了。我们打算把详细信息设计为子文档存储。
1) linq方式实现
1. 新建数据描述类,描述用户信息
/// <summary>
/// 用户主要资料
/// </summary>
public class UserInfo
{
public string UserId { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
public Detail Detail { get; set; }
}
/// <summary>
/// 用户详细资料
/// </summary>
public class Detail
{
public string Address { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
2. 我们要新建一个用户业务操作类“UserBLL”。这个时候要让驱动知道UserInfo类描述了“用户资料”的字段信息,在GetMongo()方法实现了配置步骤,UserBLL完整代码如下:
public class UserBLL
{
public string connectionString = "mongodb://localhost";
public string databaseName = "myDatabase";
private Mongo mongo;
private MongoDatabase mongoDatabase;
//注意这里泛型类型为“UserInfo”
private MongoCollection<UserInfo> mongoCollection;
public UserBLL()
{
mongo = GetMongo();
mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
mongoCollection = mongoDatabase.GetCollection<UserInfo>() as MongoCollection<UserInfo>;
mongo.Connect();
}
~UserBLL()
{
mongo.Disconnect();
}
/// <summary>
/// 配置Mongo,将类UserInfo映射到集合
/// </summary>
private Mongo GetMongo()
{
var config = new MongoConfigurationBuilder();
config.Mapping(mapping =>
{
mapping.DefaultProfile(profile =>
{
profile.SubClassesAre(t => t.IsSubclassOf(typeof(UserInfo)));
});
mapping.Map<UserInfo>();
});
config.ConnectionString(connectionString);
return new Mongo(config.BuildConfiguration());
}
}
3. 接着,在“UserBLL”类中定义一个方法“InsertSomeData()”来插入一些数据:
/// <summary>
/// 插入一些数据
/// </summary>
public void InsertSomeData()
{
UserInfo userInfo1 = new UserInfo()
{
UserId = "1001",
UserName = "张三",
PassWord = "123456"
};
mongoCollection.Save(userInfo1);
UserInfo userInfo2 = new UserInfo()
{
UserId = "1002",
UserName = "李四",
PassWord = "123456",
Detail = new Detail()
{
Address = "湖北",
Age = 20,
Email = "lisi@163.com"
}
};
mongoCollection.Save(userInfo2);
UserInfo userInfo3 = new UserInfo()
{
UserId = "1003",
UserName = "王五",
PassWord = "123456",
Detail = new Detail()
{
Address = "广东",
Age = 20,
Email = "wangwu@163.com"
}
};
mongoCollection.Save(userInfo3);
UserInfo userInfo4 = new UserInfo()
{
UserId = "1004",
UserName = "赵六",
PassWord = "123456",
Detail = new Detail()
{
Address = "湖北"
}
};
mongoCollection.Save(userInfo4);
}
4. 定义一个查找数据的方法“Select”,它将查找用户详细信息中,地址在湖北的全部用户:
/// <summary>
/// 查询详细资料地址为湖北的用户信息
/// </summary>
public List<UserInfo> Select()
{
return mongoCollection.Linq().Where(x => x.Detail.Address == "湖北").ToList();
}
5. 还定义一个删除数据的方法,将删除集合全部数据:
/// <summary>
/// 删除全部用户信息
/// </summary>
public void DeleteAll()
{
mongoCollection.Remove(x => true);
}
6. 在Main方法中添加如下代码:
static void Main(string[] args)
{
UserBLL userBll = new UserBLL();
userBll.InsertSomeData();
var users = userBll.Select();
foreach (var user in users)
{
Console.WriteLine(user.UserName + "是湖北人");
};
userBll.DeleteAll();
}
7. 最后执行程序,打印如下信息:
李四是湖北人
赵六是湖北人
1) 普通实现
普通方式实现不想多讲,直接贴代码,看看与linq方式有什么区别:
class Program
{
static void Main(string[] args)
{
UserBLL userBll = new UserBLL();
userBll.InsertSomeData();
var users = userBll.Select();
foreach (var user in users)
{
Console.WriteLine(user["UserName"].ToString() + "是湖北人");
};
userBll.DeleteAll();
Console.ReadLine();
}
}
public class UserBLL
{
public string connectionString = "mongodb://localhost";
public string databaseName = "myDatabase";
public string collectionName = "UserInfo";
private Mongo mongo;
private MongoDatabase mongoDatabase;
private MongoCollection<Document> mongoCollection;
public UserBLL()
{
mongo = new Mongo(connectionString);
mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>;
mongo.Connect();
}
~UserBLL()
{
mongo.Disconnect();
}
/// <summary>
/// 插入一些数据
/// </summary>
public void InsertSomeData()
{
Document userInfo1 = new Document();
userInfo1["UserId"] = "1001";
userInfo1["UserName"] = "张三";
userInfo1["PassWord"] = "123456";
mongoCollection.Save(userInfo1);
Document userInfo2 = new Document();
userInfo2["UserId"] = "1002";
userInfo2["UserName"] = "李四";
userInfo2["PassWord"] = "123456";
//子文档
var userInfo2Detail = new Document();
userInfo2Detail["Address"] = "湖北";
userInfo2Detail["Age"] = 20;
userInfo2Detail["Email"] = "lisi@163.com";
userInfo2["Detail"] = userInfo2Detail;
mongoCollection.Save(userInfo2);
Document userInfo3 = new Document();
userInfo3["UserId"] = "1003";
userInfo3["UserName"] = "王五";
userInfo3["PassWord"] = "123456";
var userInfo3Detail = new Document();
userInfo3Detail["Address"] = "广东";
userInfo3Detail["Age"] = 20;
userInfo3Detail["Email"] = "wangwu@163.com";
userInfo3["Detail"] = userInfo3Detail;
mongoCollection.Save(userInfo3);
Document userInfo4 = new Document();
userInfo4["UserId"] = "1004";
userInfo4["UserName"] = "赵六";
userInfo4["PassWord"] = "123456";
var userInfo4Detail = new Document();
userInfo4Detail["Address"] = "湖北";
userInfo4["Detail"] = userInfo4Detail;
mongoCollection.Save(userInfo4);
}
/// <summary>
/// 查询详细资料地址为湖北的用户信息
/// </summary>
public IEnumerable<Document> Select()
{
return mongoCollection.Find(new Document { { "Detail.Address", "湖北" } }).Documents;
}
/// <summary>
/// 删除全部用户信息
/// </summary>
public void DeleteAll()
{
mongoCollection.Remove(new Document { });
}
}
最后,我们通过这段代码输出全部用户资料信息的BJSON格式:
/// <summary>
/// 打印数据BJSON
/// </summary>
public void PrintBJSON()
{
string BJSON = string.Empty;
foreach (var documet in mongoCollection.FindAll().Documents)
{
BJSON += documet.ToString();
}
Console.WriteLine(BJSON);
}
结果如下:
{ "UserId": "1001", "UserName": "张三", "PassWord": "123456", "_id": "4d80ec1ab8a4731338000001" }
{ "UserId": "1002", "UserName": "李四", "PassWord": "123456", "Detail": { "Address": "湖北", "Age": 20, "Email": "lisi@163.com" }, "_id": "4d80ec1ab8a4731338000002" }
{ "UserId": "1003", "UserName": "王五", "PassWord": "123456", "Detail": { "Address": "广东", "Age": 20, "Email": "wangwu@163.com" }, "_id": "4d80ec1ab8a4731338000003" }
{ "UserId": "1004", "UserName": "赵六", "PassWord": "123456", "Detail": { "Address": "湖北" }, "_id": "4d80ec1ab8a4731338000004" }
二、包含“子集合”的集合操作
同样举个例子:有一个学校人事管理系统要统计班级和学生的信息,现在定义了一个“班级集合”,这个集合里面的学生字段是一个“学生集合”,包含了本班全部学生。
1) linq方式实现
基础配置我就不多说了,数据类定义如下:
/// <summary>
/// 班级信息
/// </summary>
public class ClassInfo
{
public string ClassName { get; set; }
public List<Student> Students { get; set; }
}
/// <summary>
/// 学生信息
/// </summary>
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
查询叫“张三”的学生在哪个班级,以及他的详细信息:
(这里其实是ToList后在内存中查的,linq方式直接查询好像驱动不支持。)
public List<ClassInfo> Select()
{
return mongoCollection.Linq().ToList().Where(x => x.Students.Exists(s => s.Name == "张三")).ToList();
}
1) 普通实现
查询叫“张三”的学生在哪个班级,以及他的详细信息:
public List<Document> Select()
{
var mongocollection = mongoDatabase.GetCollection("ClassInfo");
return mongocollection.Find(new Document { { "Students.Name", "张三" } }).Documents.ToList();
}
打印数据的BJSON:
{ "_id": "4d814bae5c5f000000005f64", "ClassName": "1002", "Students": [ ] }
{ "_id": "4d814bae5c5f000000005f65", "ClassName": "1003", "Students": [ { "Name": "王五", "Age": 11 }, { "Name": "赵六", "Age": 9 } ] }
三、小结
通过本节例子我们发现,MongoDB有它独特的文档结构可以描述数据对象之间的一些关系特征。它虽然没有关系型数据库多表符合查询那样强大的表间查询方式,但也可以通过文档结构描述更灵活的关系特性,可以这么说,关系型数据库能做的,MongoDB基本上也可以做到。甚至有些关系数据库不容易做到的,MongoDB也可以轻松做到,比如,描述数据类的继承关系等。
作者:李盼(Lipan)
出处:[Lipan] (http://www.cnblogs.com/lipan/)
加载全部内容