使用MongoDB查询条目数量也是很常见的操作。这里提供一下对应的方法。

根据条件获取总数

使用collection!.CountDocuments(filter)来获取当前条件下的总数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/// <summary>
/// 根据条件获取总数
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="collName">表名</param>
/// <param name="filter">查询条件</param>
/// <returns>数量</returns>
public long Count<T>(string collName, FilterDefinition<T> filter) where T : class, new()
{
try
{
var collection = m_Database?.GetCollection<T>(collName);
return collection!.CountDocuments(filter);
}
catch (Exception ex)
{
Debug.LogError("根据条件获取总数出错:" + ex);
throw;
}
}

异步根据条件获取总数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/// <summary>
/// (异步)根据条件获取总数
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="collName">表名</param>
/// <param name="filter">查询条件</param>
/// <returns>数量</returns>
public async Task<long> CountAsync<T>(string collName,FilterDefinition<T> filter) where T : class, new()
{
try
{
var collection = m_Database?.GetCollection<T>(collName);
return await collection!.CountDocumentsAsync(filter);
}
catch (Exception ex)
{
Debug.LogError("根据条件获取总数出错:" + ex);
throw;
}
}