C# mongoDB Driver 使用对象方式最完善查询语法大全
#region 查询方法 /// <summary> /// 获取单个对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="id">objectId</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public T Get<T>(string id, string collectionName = null) { return GetAsync<T>(id, collectionName).Result; } /// <summary> /// 获取单个对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public T Get<T>(Expression<Func<T, bool>> expression, string collectionName = null) { return GetAsync(expression, collectionName).Result; } /// <summary> /// 获取单个对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public T Get<T>(FilterDefinition<T> filter, string collectionName = null) { return GetAsync(filter, collectionName).Result; } /// <summary> /// 获取单个对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public TNewProjection Get<T, TNewProjection>(Expression<Func<T, bool>> expression, Expression<Func<T, TNewProjection>> projection, string collectionName = null) { return GetAsync(expression, projection, collectionName).Result; } /// <summary> /// 获取单个对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">表名</param> /// <returns></returns> public TNewProjection Get<T, TNewProjection>(FilterDefinition<T> filter, Expression<Func<T, TNewProjection>> projection, string collectionName = null) { return GetAsync(filter, projection, collectionName).Result; } /// <summary> /// 异步获取单个对象 /// </summary> /// <param name="id">objectId</param> /// <param name="collectionName">表名</param> /// <returns></returns> public async Task<T> GetAsync<T>(string id, string collectionName) { return await GetAsync<T>(new BsonDocument("_id", id), collectionName).ConfigureAwait(false); } /// <summary> /// 异步获取单个对象 /// </summary> /// <param name="expression">筛选条件</param> /// <param name="collectionName">表名</param> /// <returns></returns> public async Task<T> GetAsync<T>(Expression<Func<T, bool>> expression, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.Find(expression).FirstOrDefaultAsync().ConfigureAwait(false); } /// <summary> /// 异步获取单个对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">表名称</param> /// <returns></returns> public async Task<TNewProjection> GetAsync<T, TNewProjection>(Expression<Func<T, bool>> expression, Expression<Func<T, TNewProjection>> projection, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.Find(expression).Project(projection).FirstOrDefaultAsync().ConfigureAwait(false); } /// <summary> /// 异步获取单个对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">表名</param> /// <returns></returns> public async Task<TNewProjection> GetAsync<T, TNewProjection>(FilterDefinition<T> filter, Expression<Func<T, TNewProjection>> projection, string collectionName) { var collection = GetCollection<T>(collectionName); return await collection.Find(filter).Project(projection).FirstOrDefaultAsync().ConfigureAwait(false); } public async Task<T> GetAsync<T>(FilterDefinition<T> filter, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.Find(filter).FirstOrDefaultAsync().ConfigureAwait(false); } /// <summary> /// 获取集合 /// </summary> /// <returns></returns> public List<T> GetAll<T>(string collectionName = null) { return GetAllAsync<T>(collectionName).Result; } /// <summary> /// 异步获取集合 /// </summary> /// <returns></returns> public async Task<List<T>> GetAllAsync<T>(string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.Find(new BsonDocument()).ToListAsync().ConfigureAwait(false); } /// <summary> /// 查询 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public List<T> Find<T>(Expression<Func<T, bool>> expression, string collectionName = null) { return FindAsync(expression, collectionName).Result; } /// <summary> /// 查询 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public List<TNewProjection> Find<T, TNewProjection>(Expression<Func<T, bool>> expression, Expression<Func<T, TNewProjection>> projection, string collectionName = null) { return FindAsync(expression, projection, collectionName).Result; } /// <summary> /// 查询 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public List<T> Find<T>(FilterDefinition<T> filter, string collectionName = null) { return FindAsync(filter, collectionName).Result; } /// <summary> /// 查询 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public List<TNewProjection> Find<T, TNewProjection>(FilterDefinition<T> filter, Expression<Func<T, TNewProjection>> projection, string collectionName = null) { return FindAsync(filter, projection, collectionName).Result; } /// <summary> /// 获取记录数 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="collectionName">集合名称</param> /// <returns></returns> public long Count<T>(string collectionName = null) { return CountAsync<T>(new BsonDocument(), collectionName).Result; } /// <summary> /// 获取记录数 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public long Count<T>(Expression<Func<T, bool>> expression, string collectionName = null) { return CountAsync(expression, collectionName).Result; } /// <summary> /// 获取记录数 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public long Count<T>(FilterDefinition<T> filter, string collectionName = null) { return CountAsync(filter, collectionName).Result; } /// <summary> /// 异步获取记录数 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<long> CountAsync<T>(Expression<Func<T, bool>> expression, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.CountAsync(expression).ConfigureAwait(false); } /// <summary> /// 异步获取记录数 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<long> CountAsync<T>(FilterDefinition<T> filter, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.CountAsync(filter).ConfigureAwait(false); } /// <summary> /// 获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public List<T> PageList<T>(int pageIndex, int pageSize, string collectionName = null) { return PageListAsync<T>(pageIndex, pageSize, collectionName).Result; } /// <summary> /// 获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public List<TNewProjection> PageList<T, TNewProjection>(int pageIndex, int pageSize, Expression<Func<T, TNewProjection>> projection, string collectionName) { return PageListAsync(pageIndex, pageSize, projection, collectionName).Result; } /// <summary> /// 获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="where">筛选条件</param> /// <param name="sort">排序条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public List<T> PageList<T>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, SortDefinition<T> sort, string collectionName = null) { return PageListAsync(pageIndex, pageSize, where, sort, collectionName).Result; } /// <summary> /// 获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="where">筛选条件</param> /// <param name="sort">排序条件</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public List<TNewProjection> PageList<T, TNewProjection>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, SortDefinition<T> sort, Expression<Func<T, TNewProjection>> projection, string collectionName = null) { return PageListAsync(pageIndex, pageSize, where, sort, projection, collectionName).Result; } /// <summary> /// 获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="filter">筛选条件</param> /// <param name="sort">排序条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public List<T> PageList<T>(int pageIndex, int pageSize, FilterDefinition<T> filter, SortDefinition<T> sort, string collectionName) { return PageListAsync(pageIndex, pageSize, filter, sort, collectionName).Result; } /// <summary> /// 获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="filter">过滤器</param> /// <param name="sort">排序条件</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public List<TNewProjection> PageList<T, TNewProjection>(int pageIndex, int pageSize, FilterDefinition<T> filter, SortDefinition<T> sort, Expression<Func<T, TNewProjection>> projection, string collectionName = null) { return PageListAsync(pageIndex, pageSize, filter, sort, projection, collectionName).Result; } /// <summary> /// 异步获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<List<T>> PageListAsync<T>(int pageIndex, int pageSize, string collectionName) { var collection = GetCollection<T>(collectionName); return await collection.Find(new BsonDocument()) .Skip((pageIndex - 1) * pageSize) .Limit(pageSize) .ToListAsync() .ConfigureAwait(false); } /// <summary> /// 异步获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<List<TNewProjection>> PageListAsync<T, TNewProjection>(int pageIndex, int pageSize, Expression<Func<T, TNewProjection>> projection, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.Find(new BsonDocument()) .Project(projection) .Skip((pageIndex - 1) * pageSize) .Limit(pageSize) .ToListAsync() .ConfigureAwait(false); } public async Task<List<T>> PageListAsync<T>(int pageIndex, int pageSize, FilterDefinition<T> filter, SortDefinition<T> sort, string collectionName) { var collection = GetCollection<T>(collectionName); return await collection.Find(filter) .Sort(sort) .Skip((pageIndex - 1) * pageSize) .Limit(pageSize) .ToListAsync() .ConfigureAwait(false); } /// <summary> /// 异步获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="filter">过滤器</param> /// <param name="sort">排序条件</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<List<TNewProjection>> PageListAsync<T, TNewProjection>(int pageIndex, int pageSize, FilterDefinition<T> filter, SortDefinition<T> sort, Expression<Func<T, TNewProjection>> projection, string collectionName) { var collection = GetCollection<T>(collectionName); return await collection.Find(filter) .Project(projection) .Sort(sort) .Skip((pageIndex - 1) * pageSize) .Limit(pageSize) .ToListAsync() .ConfigureAwait(false); } /// <summary> /// 异步获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="where">筛选条件</param> /// <param name="sort">排序条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<List<T>> PageListAsync<T>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, SortDefinition<T> sort, string collectionName) { var collection = GetCollection<T>(collectionName); return await collection.Find(where) .Sort(sort) .Skip((pageIndex - 1) * pageSize) .Limit(pageSize) .ToListAsync() .ConfigureAwait(false); } /// <summary> /// 异步获取分页数据 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="pageIndex">页次</param> /// <param name="pageSize">页大小</param> /// <param name="where">筛选条件</param> /// <param name="sort">排序条件</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<List<TNewProjection>> PageListAsync<T, TNewProjection>(int pageIndex, int pageSize, Expression<Func<T, bool>> where, SortDefinition<T> sort, Expression<Func<T, TNewProjection>> projection, string collectionName) { var collection = GetCollection<T>(collectionName); return await collection.Find(where) .Project(projection) .Sort(sort) .Skip((pageIndex - 1) * pageSize) .Limit(pageSize) .ToListAsync() .ConfigureAwait(false); } /// <summary> /// 异步查询 /// </summary> /// <param name="expression">筛选条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<List<T>> FindAsync<T>(Expression<Func<T, bool>> expression, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.Find(expression).ToListAsync().ConfigureAwait(false); } /// <summary> /// 异步查询 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="expression">查询条件</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<List<TNewProjection>> FindAsync<T, TNewProjection>( Expression<Func<T, bool>> expression, Expression<Func<T, TNewProjection>> projection, string collectionName) { var collection = GetCollection<T>(collectionName); return await collection.Find(expression).Project(projection).ToListAsync().ConfigureAwait(false); } /// <summary> /// 异步查询 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<List<T>> FindAsync<T>(FilterDefinition<T> filter, string collectionName) { var collection = GetCollection<T>(collectionName); return await collection.Find(filter).ToListAsync().ConfigureAwait(false); } /// <summary> /// 异步查询 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <typeparam name="TNewProjection">新实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="projection">新实体映射</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<List<TNewProjection>> FindAsync<T, TNewProjection>(FilterDefinition<T> filter, Expression<Func<T, TNewProjection>> projection, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.Find(filter).Project(projection).ToListAsync().ConfigureAwait(false); }
/// <summary> /// 聚合查询 /// </summary> /// <param name="collectionName"></param> /// <param name="pipelineStage"></param> /// <returns></returns> private List<T> AggregateQuery<T>(IEnumerable<IPipelineStageDefinition> pipelineStage) { var pipeline = new PipelineStagePipelineDefinition<T, T>(pipelineStage); var result = _collection.Aggregate(pipeline); return result.ToList(); } /// <summary> /// 聚合查询 /// </summary> /// <param name="collectionName"></param> /// <param name="pipelineStage"></param> /// <returns></returns> private TO Aggregate<T,TO>(IEnumerable<IPipelineStageDefinition> pipelineStage) { var pipeline = new PipelineStagePipelineDefinition<T, TO>(pipelineStage); var result = _collection.Aggregate(pipeline); return result.FirstOrDefault(); } private List<TO> AggregateQuery<T,TO>(IEnumerable<IPipelineStageDefinition> pipelineStage) { var pipeline = new PipelineStagePipelineDefinition<T, TO>(pipelineStage); var result = _collection.Aggregate(pipeline); return result.ToList(); } /// <summary> /// /// </summary> /// <typeparam name="TG">group by字段类型</typeparam> /// <typeparam name="TO">输出类型</typeparam> /// <param name="match"></param> /// <param name="groupby"></param> /// <param name="groupValue"></param> /// <returns></returns> public List<TO> AggregateQuery<T,TG, TO>(Expression<Func<T, bool>> match, Expression<Func<T, TG>> groupby, Expression<Func<IGrouping<TG, T>, TO>> groupValue) { var pipelineStageDefinitions = new IPipelineStageDefinition[] { PipelineStageDefinitionBuilder.Match(match), PipelineStageDefinitionBuilder.Group(groupby,groupValue) }; return AggregateQuery<TO>(pipelineStageDefinitions); }
#endregion #region 插入方法 /// <summary> /// 插入 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="value">对象</param> /// <param name="collectionName">集合名称</param> public void Insert<T>(T value, string collectionName = null) { InsertAsync(value, collectionName).Wait(); } /// <summary> /// 异步插入 /// </summary> /// <param name="value">对象</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task InsertAsync<T>(T value, string collectionName = null) { var collection = GetCollection<T>(collectionName); await collection.InsertOneAsync(value).ConfigureAwait(false); } /// <summary> /// 批量插入 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="values">对象集合</param> /// <param name="collectionName">集合名称</param> public void BatchInsert<T>(IEnumerable<T> values, string collectionName = null) { BatchInsertAsync(values, collectionName).Wait(); } /// <summary> /// 异步批量插入 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="values">对象集合</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task BatchInsertAsync<T>(IEnumerable<T> values, string collectionName = null) { var collection = GetCollection<T>(collectionName); await collection.InsertManyAsync(values).ConfigureAwait(false); } #endregion #region 更新方法 /// <summary> /// 覆盖更新 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="value">对象</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public ReplaceOneResult Update<T>(T value, string collectionName = null) { return UpdateAsync(value, collectionName).Result; } /// <summary> /// 局部更新 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="id">记录ID</param> /// <param name="update">更新条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public UpdateResult Update<T>(ObjectId id, UpdateDefinition<T> update, string collectionName = null) { return UpdateAsync(new BsonDocument("_id", id), update, collectionName).Result; } /// <summary> /// 局部更新 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="update">更新条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public UpdateResult Update<T>(Expression<Func<T, bool>> expression, UpdateDefinition<T> update, string collectionName = null) { return UpdateAsync(expression, update, collectionName).Result; } /// <summary> /// 局部更新 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="update">更新条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public UpdateResult UpdateMany<T>(Expression<Func<T, bool>> expression, UpdateDefinition<T> update, string collectionName = null) { return UpdateManyAsync(expression, update, collectionName).Result; } public UpdateResult Update<T>(FilterDefinition<T> expression, UpdateDefinition<T> update, string collectionName = null) { return UpdateAsync(expression, update, collectionName).Result; } /// <summary> /// 异步局部更新(仅更新一条记录) /// <para><![CDATA[expression 参数示例:x => x.Id == 1 && x.Age > 18 && x.Gender == 0]]></para> /// <para><![CDATA[entity 参数示例:y => new T{ RealName = "Ray", Gender = 1}]]></para> /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="entity">更新条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public UpdateResult Update<T>(Expression<Func<T, bool>> expression, Expression<Action<T>> entity, string collectionName = null) { return UpdateAsync(expression, entity, collectionName).Result; } /// <summary> /// 异步局部更新(仅更新一条记录) /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="update">更新条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<UpdateResult> UpdateAsync<T>(FilterDefinition<T> filter, UpdateDefinition<T> update, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.UpdateOneAsync(filter, update).ConfigureAwait(false); } /// <summary> /// 异步局部更新(仅更新一条记录) /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="update">更新条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<UpdateResult> UpdateAsync<T>(Expression<Func<T, bool>> expression, UpdateDefinition<T> update, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.UpdateOneAsync(expression, update).ConfigureAwait(false); } /// <summary> /// 异步局部更新(仅更新多条记录) /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="update">更新条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<UpdateResult> UpdateManyAsync<T>(Expression<Func<T, bool>> expression, UpdateDefinition<T> update, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.UpdateManyAsync(expression, update).ConfigureAwait(false); } /// <summary> /// 异步局部更新(仅更新一条记录) /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="entity">更新条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<UpdateResult> UpdateAsync<T>(Expression<Func<T, bool>> expression, Expression<Action<T>> entity, string collectionName = null) { var fieldList = new List<UpdateDefinition<T>>(); var param = entity.Body as MemberInitExpression; if (param != null) { foreach (var item in param.Bindings) { var propertyName = item.Member.Name; object propertyValue = null; var memberAssignment = item as MemberAssignment; if (memberAssignment == null) continue; if (memberAssignment.Expression.NodeType == ExpressionType.Constant) { var constantExpression = memberAssignment.Expression as ConstantExpression; if (constantExpression != null) propertyValue = constantExpression.Value; } else { propertyValue = Expression.Lambda(memberAssignment.Expression, null).Compile().DynamicInvoke(); } if (propertyName != "_id") //实体键_id不允许更新 { fieldList.Add(Builders<T>.Update.Set(propertyName, propertyValue)); } } } var collection = GetCollection<T>(collectionName); return await collection.UpdateOneAsync(expression, Builders<T>.Update.Combine(fieldList)).ConfigureAwait(false); } /// <summary> /// 异步覆盖更新 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="value">对象</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<ReplaceOneResult> UpdateAsync<T>(T value, string collectionName) { var collection = GetCollection<T>(collectionName); return await collection.ReplaceOneAsync( new BsonDocument("_id", new ObjectId(typeof(T).GetProperty("Id").GetValue(value).ToString())), value).ConfigureAwait(false); } #endregion #region 删除方法 /// <summary> /// 删除指定对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="id">对象Id</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public DeleteResult Delete<T>(ObjectId id, string collectionName = null) { return DeleteAsync<T>(id, collectionName).Result; } /// <summary> /// 删除指定对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">查询条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public DeleteResult Delete<T>(Expression<Func<T, bool>> expression, string collectionName = null) { return DeleteAsync(expression, collectionName).Result; } /// <summary> /// 异步删除指定对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="id">对象Id</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<DeleteResult> DeleteAsync<T>(ObjectId id, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.DeleteOneAsync(new BsonDocument("_id", id)).ConfigureAwait(false); } /// <summary> /// 异步删除指定对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">查询条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<DeleteResult> DeleteAsync<T>(Expression<Func<T, bool>> expression, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.DeleteOneAsync(expression).ConfigureAwait(false); } /// <summary> /// 批量删除对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="ids">ID集合</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public DeleteResult BatchDelete<T>(IEnumerable<ObjectId> ids, string collectionName = null) { return BatchDeleteAsync<T>(ids, collectionName).Result; } /// <summary> /// 批量删除对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public DeleteResult BatchDelete<T>(FilterDefinition<T> filter, string collectionName = null) { return BatchDeleteAsync(filter, collectionName).Result; } /// <summary> /// 批量删除对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public DeleteResult BatchDelete<T>(Expression<Func<T, bool>> expression, string collectionName = null) { return BatchDeleteAsync(expression, collectionName).Result; } /// <summary> /// 异步批量删除对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="ids">ID集合</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<DeleteResult> BatchDeleteAsync<T>(IEnumerable<ObjectId> ids, string collectionName = null) { var filter = Builders<T>.Filter.In("_id", ids); var collection = GetCollection<T>(collectionName); return await collection.DeleteManyAsync(filter).ConfigureAwait(false); } /// <summary> /// 异步批量删除对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<DeleteResult> BatchDeleteAsync<T>(FilterDefinition<T> filter, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.DeleteManyAsync(filter).ConfigureAwait(false); } /// <summary> /// 异步批量删除对象 /// </summary> /// <typeparam name="T">数据库实体类型</typeparam> /// <param name="expression">筛选条件</param> /// <param name="collectionName">集合名称</param> /// <returns></returns> public async Task<DeleteResult> BatchDeleteAsync<T>(Expression<Func<T, bool>> expression, string collectionName = null) { var collection = GetCollection<T>(collectionName); return await collection.DeleteManyAsync(expression).ConfigureAwait(false); } #endregion
内嵌数组增加元素操作
(一) Update.Set()方法 替换内嵌数组(不推荐使用)
此方法主要使用操作符[$set],它的思路是先将内嵌文档的父元素查找出来,然后对子文档数组进行增删改操作,最后将子文档数组重新替换。此方式性能较低,除非涉及到大批量更改,否则不推荐使用。
#region 方法一. 查出sensor再更新Records, $set操作 - 随机插入100个元素(不推荐) // 查询需修改的sensorNode对象 var sensor = await _sensorNodes.Find(s => s.Id == _sensorNodeId).FirstOrDefaultAsync(); // 往Records里面增加随机元素 sensor.Records.AddRange(GetRandomRecord(100)); // 构建update Bson, 将原有Records替换为新的Records var update = Builders<SensorNode>.Update.Set(d => d.Records, sensor.Records); // 使用Update方法 await _sensorNodes.UpdateOneAsync(s => s.Id == _sensorNodeId, update); #endregion
(二)Update.Push()方法 直接将元素压入内嵌数组(推荐)
此方法主要使用操作符[$push]来增加元素到子文档数组,性能好,推荐使用。
// 构建update Bson ,添加一条记录使用Push方法 var updateOne = Builders<SensorNode>.Update.Push(d => d.Records, GetRandomRecord(1).First()); // 更新 await _sensorNodes.UpdateOneAsync(s => s.Id == _sensorNodeId, updateMany);
(三) Update.PushEach()方法 将多个元素压入内嵌数组(推荐)
此方法使用的也是[$push]操作符,只是在生成BsonDocument时允许接收数组。
#region 方法二. $push操作 - 随机插入100个元素(推荐) // 构建update Bson 添加多条记录使用PushEach方法 var updateMany = Builders<SensorNode>.Update.PushEach(d => d.Records, GetRandomRecord(100)); // 更新 await _sensorNodes.UpdateOneAsync(s => s.Id == _sensorNodeId, updateMany); #endregion
内嵌数组删除元素操作
(一) Update.Set()方法 替换内嵌数组(不推荐使用)
此方式思路和增加元素的思路一致,性能较低,不推荐使用。
#region 方法一 . $set方式删除 - 删除前5个元素(不推荐) // 查询需修改的sensorNode对象 var sensor = await _sensorNodes.Find(s => s.Id == _sensorNodeId).FirstOrDefaultAsync(); // 删除Record for (int i = 0; i < 5; i++) { sensor.Records.RemoveAt(i); } // 构建update Bson, 将原有Records替换为新的Records var update = Builders<SensorNode>.Update.Set(d => d.Records, sensor.Records); // 使用Update方法 await _sensorNodes.UpdateOneAsync(s => s.Id == _sensorNodeId, update); #endregion
(二) Update.Pull()方法 Pull删除一个元素(推荐)
// 假设需要删除的Record已经被查询转换为对象,那么使用Pull方式删除一个元素 var record = new Record() { Data = 1670941112.0, RecorDateTime = DateTime.Parse("2018-03-16T09:36:14.930Z") }; // 构建Pull删除Bson var update = Builders<SensorNode>.Update.Pull(s => s.Records, record); // 使用Update方法 await _sensorNodes.UpdateOneAsync(s => s.Id == _sensorNodeId, update);
(三)Update.PullFilter()方法 删除过滤器删除元素(推荐)
#region 方法三. PullFilter方式删除 - 删除符合Filter条件的元素(推荐) // 如果r.Data == 339119843.0,那么从数组中删除 var update = Builders<SensorNode>.Update.PullFilter(s => s.Records, r => r.Data == 339119843.0); await _sensorNodes.UpdateOneAsync(s => s.Id == _sensorNodeId, update); #endregion
内嵌数组修改元素操作
(一) Update.Set() Set先查询后修改(不推荐)
此方式性能较低,不推荐。
#region 方法一. $set方式修改(将某个元素记录时间改为最小值) - 先查询后修改(不推荐) // 查询需修改的sensorNode对象 var sensor = await _sensorNodes.Find(s => s.Id == _sensorNodeId).FirstOrDefaultAsync(); // 修改Record值 sensor.Records[0].RecorDateTime = DateTime.MinValue; // 构建update Bson, 将原有Records替换为新的Records var update = Builders<SensorNode>.Update.Set(d => d.Records, sensor.Records); // 使用Update方法 await _sensorNodes.UpdateOneAsync(s => s.Id == _sensorNodeId, update); #endregion
(二) Update.Set() 配合过滤器修改(推荐)
在数据库内部完成过滤和修改,性能高,推荐使用。
#region 方法二. $set方式修改(将Data = 1835821478.0的元素记录时间改为最大值) - 直接过滤修改(推荐) // 构造filter var filter = Builders<SensorNode>.Filter.Where(s => s.Id == _sensorNodeId) & Builders<SensorNode>.Filter.Where(d => d.Records.Any(r => r.Data == 1835821478.0)); // 执行更新 var update = Builders<SensorNode>.Update.Set(d => d.Records[-1].RecorDateTime, DateTime.MaxValue); await _sensorNodes.UpdateOneAsync(filter, update); #endregion
内嵌数组查找元素操作(Linq)
对于内嵌数组/文档的查询,在.net里建议直接使用Linq或拼接BsonDocument。笔者着重使用Linq方式。
需要先using MongoDB.Driver.Linq,否则Linq无法使用。
(一)Linq查询一条记录(推荐)
主要是SelectMany()方法的使用,此方法用于选择一个数组。
#region SelectMany查询内嵌数组(查询Data = 1340695206.0的第一条记录) - (推荐) // 转换为Queryable var result = await _sensorNodes.AsQueryable() // 查找对应的sensorNode .Where(s => s.Id == _sensorNodeId) // 选择Records内嵌数组 .SelectMany(s => s.Records) // 查找Data == 1340695206.0的元素 .Where(r => r.Data == 1340695206.0) // 取第一个 .FirstOrDefaultAsync(); #endregion
(二)Linq查询分页 (推荐)
主要区别使用SelectMany其它与EF Linq方式差不多
#region SelectMany、Skip、Take内嵌数组排序分页 - (推荐) // 页码 var index = 4; // 页面大小 var size = 10; // 转换为Queryable var page = await _sensorNodes.AsQueryable() // 查找对应的sensorNode .Where(s => s.Id == _sensorNodeId) // 选择Records内嵌数组 .SelectMany(s => s.Records) // 根据记录时间排序 .OrderBy(r => r.RecorDateTime) // 跳过 index - 1页数据 .Skip((index - 1) * size) // 选取一页数据 .Take(size) // 转换为集合 .ToListAsync(); #endregion
使用对象方式进行聚合查询(Linq)
//获取总数,一个样本只获取一条,where是linq lambda表达式 Expression<Func<ReportRecord, int>> groupby = g => g.SampleId; Expression<Func<MongoAggregateCnt, int>> groupbyCnt = g => 1; var conection = MongoDbManager<ReportRecord>.GetInstance() .BuildAnnotationDb() .GetCollection(ConstVar.ReportTable); var pipelineStageDefinitions = new IPipelineStageDefinition[] { PipelineStageDefinitionBuilder.Match(where), PipelineStageDefinitionBuilder.Group(groupby,v => new MongoAggregateCnt{cnt = v.Key}), PipelineStageDefinitionBuilder.Group(groupbyCnt,v => new MongoAggregateCnt{cnt = v.Count()}) }; var totalO = conection.Aggregate<MongoAggregateCnt>(pipelineStageDefinitions).FirstOrDefault(); total = totalO?.cnt??0; /// <summary> /// mongo 聚合总数 /// </summary> public class MongoAggregateCnt { public int cnt { get; set; } }
/// <summary> /// 聚合查询 /// </summary> /// <param name="collectionName"></param> /// <param name="pipelineStage"></param> /// <returns></returns> private List<T> AggregateQuery(IEnumerable<IPipelineStageDefinition> pipelineStage) {
var pipeline = new PipelineStagePipelineDefinition<T, T>(pipelineStage); var result = _collection.Aggregate(pipeline); return result.ToList(); } /// <summary> /// 聚合查询 /// </summary> /// <param name="collectionName"></param> /// <param name="pipelineStage"></param> /// <returns></returns> private TO Aggregate<TO>(IEnumerable<IPipelineStageDefinition> pipelineStage) { var pipeline = new PipelineStagePipelineDefinition<T, TO>(pipelineStage); var result = _collection.Aggregate(pipeline); return result.FirstOrDefault(); } private List<TO> AggregateQuery<TO>(IEnumerable<IPipelineStageDefinition> pipelineStage) {
var pipeline = new PipelineStagePipelineDefinition<T, TO>(pipelineStage); var result = _collection.Aggregate(pipeline); return result.ToList(); } /// <summary> /// /// </summary> /// <typeparam name="TG">group by字段类型</typeparam> /// <typeparam name="TO">输出类型</typeparam> /// <param name="match"></param> /// <param name="groupby"></param> /// <param name="groupValue"></param> /// <returns></returns> public List<TO> AggregateQuery<TG, TO>(Expression<Func<T, bool>> match, Expression<Func<T, TG>> groupby, Expression<Func<IGrouping<TG, T>, TO>> groupValue) { var pipelineStageDefinitions = new IPipelineStageDefinition[] { PipelineStageDefinitionBuilder.Match(match), PipelineStageDefinitionBuilder.Group(groupby,groupValue) }; return AggregateQuery<TO>(pipelineStageDefinitions); }