.netcore mongodb 分页+模糊查询+多条件查询
.netcore MongoDB.Driver 版本才2.8 与aspnet差距太大,网上找很多资料没有现成的代码。
public override async Task<PagerList<NewsContentDto>> PagerQueryAsync(NewsContentQuery parameter) { FilterDefinitionBuilder<NewsContentDto> builder = Builders<NewsContentDto>.Filter; string p = parameter.Keyword == null? $".*{Regex.Escape("")}.*": $".*{Regex.Escape(parameter.Keyword)}.*"; FilterDefinition <NewsContentDto> filter2 = builder.Regex("title", new BsonRegularExpression(new Regex(p, RegexOptions.IgnoreCase))); //var filter1 = Builders<T>.Filter.Regex("title", new BsonRegularExpression(new Regex(".*" + Regex.Escape("英超") + ".*", RegexOptions.IgnoreCase))); //var filter1 = Filter.Regex(x => x.EnglishName, new MongoDB.Bson.BsonRegularExpression(parameter.Keyword, "i")); //BsonDocument filter = new BsonDocument {{"title", $"/{parameter.Keyword}/" } }; //if(parameter.classifyId>0) filter.Add("classifyId", parameter.classifyId); var query = new QueryMongoParameter<NewsContentDto>(parameter, "news_content", filter2); var ret = await MongoContext.PagerQueryAsync(query); return ret; }
分页查询
public async Task<PagerList<T>> PagerQueryAsync<T>(QueryMongoParameter<T> query) { var skip = (query.Page - 1) * query.PageSize; var collection = _database.GetCollection<T>(query.CollectName); var data = await collection.Find(query.Filter).Sort(query.Sort).Project(query.Projection).Skip(skip).Limit(query.PageSize).ToListAsync(); var total = await collection.CountAsync(query.Filter); var ret = new List<T>(); data.ForEach(d => { string s = d.ToString().Replace("\"_id\"", "\"id\""); ret.Add(Helpers.Json.ToObject<T>(s)); }); return new PagerList<T>(query.Page, query.PageSize, (int)total, ret); }
补充
public class PageMongoParameter : ParameterBase { public BsonDocument Sort { get; } public BsonDocument Skip { get; } public BsonDocument Limit { get;} public BsonDocument Filter2 { get; } public BsonDocument[] Pipeline { get; set; } public PageMongoParameter(PageRequest req, string collectName, BsonDocument filter=null,BsonDocument sort=null, BsonDocument filter2 = null) { CollectName = collectName; Page = req.pageindex; PageSize = req.pagesize; Limit = new BsonDocument { { "$limit", PageSize } }; Skip = new BsonDocument { { "$skip", (Page-1)*PageSize} }; if (sort == null) { if (!string.IsNullOrEmpty(req.order)) Sort = new BsonDocument { { "$sort", new BsonDocument { { req.order, 1 } } } }; } else { Sort = sort; } if (filter != null && filter2==null) { var dom = filter.GetElement(0); Filter2 = BsonDocument.Parse(dom.Value.ToJson()); } Filter2 = Filter2 ?? new BsonDocument(); if (filter == null && Sort == null) Pipeline = new[] {Skip, Limit}; else { if(filter!=null && Sort != null) Pipeline = new[] { filter,Skip, Limit,Sort }; else Pipeline = filter == null ? new[] {Skip, Limit, Sort} : new[] { filter,Skip, Limit}; } } }