#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 - ) * 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 - ) * 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 - ) * 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 - ) * 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 - ) * 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 - ) * 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);
} #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());
// 构建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().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());
// 更新
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 = ; i < ; 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[].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[-].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 = ;
// 页面大小
var size = ;
// 转换为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 - ) * size)
// 选取一页数据
.Take(size)
// 转换为集合
.ToListAsync();
#endregion

C# mongoDB Driver 使用对象方式查询语法大全的更多相关文章

  1. mongoDB 高级查询语法

    http://www.cnblogs.com/ITAres/articles/2084794.html本文参考自官方的手册:http://www.mongodb.org/display/DOCS/Ad ...

  2. MongoDB查询语法

    mongoDb是非关系型数据库,用习惯了mssql,mysql等数据库的需要转换一下思维 mongoDb存的是与js的json结构一样的文档,表中的每一条记录都可以结构不同 1,大于,小于,大于等于, ...

  3. php MongoDB driver 查询实例

    //是否只查mx $mx_on_switch = I("post.mx_on_switch"); //mx模糊查询 $mx_vague_check = I("post.m ...

  4. (转)经典SQL查询语句大全

    (转)经典SQL查询语句大全 一.基础1.说明:创建数据库CREATE DATABASE database-name2.说明:删除数据库drop database dbname3.说明:备份sql s ...

  5. MYSQL查询语句大全集锦

    MYSQL查询语句大全集锦 1:使用SHOW语句找出在服务器上当前存在什么数据库: mysql> SHOW DATABASES; 2:2.创建一个数据库MYSQLDATA mysql> C ...

  6. SQL查询语句大全集锦

    SQL查询语句大全集锦 一. 简单查询 简单的Transact-SQL查询只包括选择列表.FROM子句和WHERE子句.它们分别说明所查询列.查询的 表或视图.以及搜索条件等. 例如,下面的语句查询t ...

  7. MYSQL 语法大全自己总结的

    mysql语法大全 --------数据链接---------------------数据库服务启动net start mysql --关闭服务net stop mysql --登录 -u,-p后面不 ...

  8. MongoDB Driver 简单的CURD

    c#中我们可以使用MongoDB.Driver驱动进行对MongoDB数据库的增删改查. 首先需要在NuGet中安装驱动 安装完毕后会发现会有三个引用 其中 MongoDB.Driver和MongoD ...

  9. ThinkPHP 数据库操作(三) : 查询方法、查询语法、链式操作

    查询方法 条件查询方法 where 方法 可以使用 where 方法进行 AND 条件查询: Db::table('think_user') ->where('name','like','%th ...

随机推荐

  1. Spark记录-SparkSQL一些操作

    scala>val spark=new org.apache.spark.sql.SQLContext(sc) user.json {"age":"45" ...

  2. js鼠标移入移出效果【原】

    <HTML> <HEAD> <!-- meta 解释 : http://www.haorooms.com/post/html_meta_ds --> <met ...

  3. POJ 2796[UVA 1619] Feel Good

    Feel Good Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 16786   Accepted: 4627 Case T ...

  4. luogu 1026 统计单词个数

    此题 字符串匹配+dp 确实我的kmp,哈希需要练一练了,忘干净可咋办 补救用下string,十分方便 e.g: 1.询问a[i]是否是x子串,可以截取并判断前缀 x为截取串 x.find(a[i]) ...

  5. 7、完整版的strcpy函数

    char * strcpy( char *strDest, const char *strSrc ) { assert( (strDest != NULL) && (strSrc != ...

  6. Database学习 - mysql 连接数据库 库操作

    连接数据库 语法格式: mysql -h 服务器IP -P 端口号 -u用户名 -p密码 --prompt 命令提示符 --delimiter 指定分隔符 示例: mysql -h 127.0.0.1 ...

  7. Apple Watch 开发详解

    Apple Watch 开发详解 Apple Watch现在对于第三方开发者来说更多的还是一块额外的屏幕.暂时WatchKit没有能给出足够的接口.现在Watch App的主要运算逻辑需要依赖iPho ...

  8. 用accessKey设置快捷键

    <!DOCTYPE html> <html> <body> <a href="http://www.w3school.com.cn/html/&qu ...

  9. python中的%s%是什么意思

    它是一个字符串格式化语法(它从C借用). 请参阅  “格式化字符串”: Python支持将值格式化为字符串.虽然这可以包括非常复杂的表达式,但最基本的用法是将值插入到%s 占位符的字符串中  . 编辑 ...

  10. SpringMVC参数绑定(四)

    1.默认支持的参数类型 处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值. HttpServletRequest 通过request对象获取请求信息 HttpServletResponse ...