/// <summary> /// 内嵌文档分页 /// </summary> public void SunPageList() { //投影定义创建器:ProjectionDefinitionBuilder //用ProjectionDefinition过滤子文档 ProjectionDefinitionBuilder <Model2> projBuilder = Builders <Model2> .Projection; //Include :确定要包含哪些字段值(即给哪些字段赋值) //Slice:获得子文档集合分片,第一个参数field指取出的子文档集合,第二各参数skip指跳过多少个子文档,第三个参数limit取出多少个 ProjectionDefinition <Model2> proj = projBuilder.Include(m => m.Field2C).Slice(m => m.Field2C, 1, 3); //过滤条件是Field2A=2 Model2 doc = mongoDBService.SubdocumentPageList <Model2>(collectionName, m => m.Field2A == "2", proj); }
/// <summary> /// 查找某一个子文档 ///</summary> public void QueryChild() { FilterDefinitionBuilder <Model2> filterBuilder = Builders <Model2> .Filter; //找到父文档,过滤条件为Field2A=2并且Field2B=“2018-01-21T16:00:00.000Z” FilterDefinition <Model2> filterFather = filterBuilder.Eq(doc => doc.Field2A, "2") & filterBuilder.Eq(doc => doc.Field2B, DateTime.Parse("2018-01-21T16:00:00.000Z")); //投影定义创建器:ProjectionDefinitionBuilder //用ProjectionDefinition过滤子文档,投影器创建器作用于Field2C,他是一个集合,用来保存多个子文档;过滤条件为Field1C = 3.1415926 ProjectionDefinitionBuilder <Model2> projBuilder = Builders <Model2> .Projection; ProjectionDefinition <Model2> proj = projBuilder.ElemMatch(listField => listField.Field2C, childfield => childfield.Field1C == 3.1415926); FindOptions options = new FindOptions() { AllowPartialResults = true }; Model2 info = mongoDBService.Single <Model2>(collectionName, filterFather, options, proj); }
/// <summary> /// 插入子文档 /// </summary> public void InsertChild() { Model1 model1 = new Model1 { Field1A = "MongoDB是一种开源文档型数据库", Field1B = 100, Field1C = 3.1415926, Field1D = 3.1415926F, Field1E = new List <string>() }; Model2 model2 = new Model2 { Id = new Guid().ToString("N"), Field2A = "1", Field2B = DateTime.Now.Date, Field2C = new List <Model1>() }; FilterDefinitionBuilder <Model2> filterBuilder = Builders <Model2> .Filter; //过滤条件字段Field2A==2 FilterDefinition <Model2> filter = filterBuilder.Eq(doc => doc.Field2A, "2"); SortDefinitionBuilder <Model1> sortBuilder = Builders <Model1> .Sort; //按字段Field1A升序排列 SortDefinition <Model1> sort = sortBuilder.Ascending(pu => pu.Field1A); //最新插入的在最前面 UpdateDefinitionBuilder <Model2> updateBuilder = Builders <Model2> .Update; //PushEach 参数含义: //field:lambda表达式,要更新的字段,这里其实是个集合,集合里的每一个元素都是一个子文档。 //values:待放入field的值,这里是一个集合,所以一次可以放入多个 //slice:约束子文档集合的大小,如果设置为null,则大小不限,如果设置为0,那么没有任何子文档可被装入其中。 //position:指定插入子文档在集合中的位置 //sort:对子文档进行排序,可以指定任意字段排序 UpdateDefinition <Model2> update = updateBuilder.PushEach(doc => doc.Field2C, new List <Model1> { model1 }, null, 0, sort); UpdateResult updateResult = mongoDBService.DocumentUpdate(collectionName, filter, update); }