回到目錄
我不得不說,mongodb官方驅動在與.net結合上做的不是很好,不是很理想,是以,我決定對它進行了二次封裝,這是顯得很必然了,每個人都希望使用簡單的對象,而對使用複雜,麻煩,容易出錯的對象盡而遠之,這是正常的,人都是喜歡懶惰的,就像程式員,也是一樣,喜歡偷懶,可能說,偷懶是程式員進步的一個标志,呵呵.
下面我是總結的幾種标準的操作,主要是針對我封裝的官方驅動而方的(MongoOfficialRepository<TEntity>)
1 插入對象和子對象
/// <summary>
/// 添加對象
/// </summary>
static public void Insert()
{
List<Person> list = new List<Person>();
for (int i = 0; i < 10; i++)
{
//添加新對象
list.Add(new Person
{
Address = new Address
{
City = "北京",
District = "鸾翔鳳集",
Province = "luanxian",
},
AddList = new List<Address>
{
new Address
{
Seconds=1,
City = "湖北",
District = "鸾翔鳳集",
Province = "luanxian",
},
new Address
{
Seconds=1,
City = "湖南",
District = "小區",
Province = "luanxian",
}
},
Age = 35,
Birthday = DateTime.Now,
LastContact = DateTime.Now,
Name = "wangwu"
});
}
repository1.Insert(list);
}
2 更新對象和子對象集合元素,這是非常不錯的功能,對于沒有必要更新的記錄,可以不去為它指派
/// <summary>
/// 集合查詢
/// </summary>
static public void Update()
{
repository1.Update<Person>(i => new Person
{
Id = "556bfd1b2683c82060c2edd0",
AddList = new List<Address>
{
new Address
{
Id = "556bfd1b2683c82060c2edd3",
City = "占占大師123",
District = "鸾翔鳳集",
Seconds=2
}
}
});
}
3 分頁,多字段查詢和排序,這是項目開發中用的最多的東西了,寫了個标準的給大家參考
/// <summary>
/// 分頁,排序,查詢
/// </summary>
static public void Select()
{
//排序和檢索
var m1 = repository1.GetModel(new
{
Address = new
{
City = "北京"
},
AddList = new
{
Seconds = 1
}
}, new { Name = OrderType.Desc }, 1, 20);
4 分組,對于需要按着按些字段進行聚合(統計,求和,總數,最大值,最小值等),及多條件查詢,這裡有不錯的執行個體
/// <summary>
/// 分組
/// </summary>
static public PagedList<Person> Group(string keyword, int? age, int page)
{
Specification<Person> spec = new TrueSpecification<Person>();
//過濾
if (!string.IsNullOrWhiteSpace(keyword))
{
spec &= new DirectSpecification<Person>(i => i.Name == keyword);
}
if (age.HasValue)
{
spec &= new DirectSpecification<Person>(i => i.Age == age);
}
//分組
var linq = from data1 in repository1.GetModel().Where(spec.SatisfiedBy())
group data1 by new
{
data1.Id,
data1.Name
} into g
select new Person
{
Id = g.Key.Id,
Name = g.Key.Name,
Total = new Total
{
Count = g.Count(),
Max = g.Max(i => i.Age),
}
};
return new PagedList<Person>(linq, page, 10);
}
OK,以上是針對我的MongoDB倉儲進行的一些二次說明,感覺還是比較有必要的,呵呵.
作者:倉儲大叔,張占嶺,
榮譽:微軟MVP
QQ:853066980
支付寶掃一掃,為大叔打賞!
