MongoDB学习笔记(四)用MongoDB的文档结构描述数据关系(6)
来源:未知 责任编辑:责任编辑 发表时间:2013-11-15 19:51 点击:次
	   
	{ "UserId": "1003", "UserName": "王五", "PassWord": "123456", "Detail": { "Address": "广东", "Age": 20, "Email": "wangwu@163.com" }, "_id": "4d80ec1ab8a4731338000003" }
{ "UserId": "1004", "UserName": "赵六", "PassWord": "123456", "Detail": { "Address": "湖北" }, "_id": "4d80ec1ab8a4731338000004" }
二、包含“子集合”的集合操作  www.2cto.com  
  同样举个例子:有一个学校人事管理系统要统计班级和学生的信息,现在定义了一个“班级集合”,这个集合里面的学生字段是一个“学生集合”,包含了本班全部学生。
   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()
{  www.2cto.com  
    return mongoCollection.Linq().ToList().Where(x => x.Students.Exists(s => s.Name == "张三")).ToList();
}
   1) 普通实现
  查询叫“张三”的学生在哪个班级,以及他的详细信息:
public List<Document> Select()
{  www.2cto.com  
    var mongocollection = mongoDatabase.GetCollection("ClassInfo");
    return mongocollection.Find(new Document { { "Students.Name", "张三" } }).Documents.ToList();
}
  打印数据的BJSON:
{ "_id": "4d814bae5c5f000000005f63", "ClassName": "1001", "Students": [ { "Name": "张三", "Age": 10 }, { "Name": "李四", "Age": 0 } ] }  www.2cto.com  
{ "_id": "4d814bae5c5f000000005f64", "ClassName": "1002", "Students": [ ] }
{ "_id": "4d814bae5c5f000000005f65", "ClassName": "1003", "Students": [ { "Name": "王五", "Age": 11 }, { "Name": "赵六", "Age": 9 } ] }
	
	
        
        
        
	
        相关新闻>>
最新推荐更多>>>
              
          - 发表评论
 - 
				
 
- 最新评论 进入详细评论页>>
 








