Visão geral
Neste guia, você pode aprender a obter uma contagem precisa e estimada do número de documentos em sua coleção.
Dados de amostra
Os exemplos deste guia usam os seguintes documentos em uma collection chamada students
:
{ "_id": 1, "name": "Jonathon Howard ", "finalGrade": 87.5 } { "_id": 2, "name": "Keisha Freeman", "finalGrade": 12.3 } { "_id": 3, "name": "Wei Zhang", "finalGrade": 99.0 } { "_id": 4, "name": "Juan Gonzalez", "finalGrade": 85.5 } { "_id": 5, "name": "Erik Trout", "finalGrade": 72.3 } { "_id": 6, "name": "Demarcus Smith", "finalGrade": 88.8 }
A seguinte classe Student
modela os documentos nesta coleção:
public class Student { public int Id { get; set; } public string Name { get; set; } public double FinalGrade { get; set; } }
Observação
Os documentos na coleção students
usam a convenção de nomenclatura de camelo. Os exemplos neste guia usam um ConventionPack
para desserializar os campos na coleção em maiúsculas e minúsculas Pascal e mapeá-los para as propriedades na classe Student
.
Para saber mais sobre serialização personalizada, consulte Serialização personalizada.
Contagem precisa
Para contar o número de documentos que correspondem ao seu filtro de consulta, utilize o método CountDocuments()
. Se você passar por um filtro de query vazio, esse método retornará o número total de documentos na coleção.
Exemplo
O exemplo a seguir conta o número de documentos em que o valor de finalGrade
é menor que 80
:
var filter = Builders<Student>.Filter.Lt(s => s.FinalGrade, 80.0); var count = _myColl.CountDocuments(filter); Console.WriteLine("Number of documents with a final grade less than 80: " + count);
Number of documents with a final grade less than 80: 2
Modificar comportamento
Você pode modificar o comportamento do CountDocuments()
passando um tipo de CountOptions
como um parâmetro. Se você não especificar nenhuma opção, o driver usará valores padrão.
Você pode definir as seguintes propriedades em um objeto CountOptions
:
Propriedade | Descrição |
---|---|
| The type of language collation to use when sorting results. See the
Collation section of this page for more information. Default: null |
| The index to use to scan for documents to count. Default: null |
| The maximum number of documents to count. Default: 0 |
| The maximum amount of time that the query can run on the server. Default: null |
| The number of documents to skip before counting. Default: 0 |
Dica
Quando você usa CountDocuments()
para retornar o número total de documentos em uma collection, o MongoDB executa uma varredura de collection. Você pode evitar uma varredura de collection e melhorar o desempenho desse método usando uma dica para aproveitar o índice incorporado no campo _id
. Utilize esta técnica somente ao chamar CountDocuments()
com um parâmetro de query vazio.
var filter = Builders<Student>.Filter.Empty; CountOptions opts = new CountOptions(){Hint = "_id_"}; var count = collection.CountDocuments(filter, opts);
Agrupamentos
Para configurar o agrupamento para sua operação, crie uma instância da classe Agrupamento.
A tabela seguinte descreve os parâmetros que o construtor do Collation
aceita. Ela também lista a propriedade de classe correspondente que você pode usar para ler o valor de cada configuração.
Parâmetro | Descrição | Propriedade de classe |
---|---|---|
| Specifies the International Components for Unicode (ICU) locale. For a list of
supported locales,
see Collation Locales and Default Parameters
in the MongoDB Server Manual. If you want to use simple binary comparison, use the Collation.Simple static
property to return a Collation object with the locale set to "simple" .Data Type: string |
|
| (Optional) Specifies whether to include case comparison. When this argument is true , the driver's behavior depends on the value of
the strength argument:- If strength is CollationStrength.Primary , the driver compares base
characters and case.- If strength is CollationStrength.Secondary , the driver compares base
characters, diacritics, other secondary differences, and case.- If strength is any other value, this argument is ignored.When this argument is false , the driver doesn't include case comparison at
strength level Primary or Secondary .Data Type: boolean Default: false |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. Data Type: CollationCaseFirst Default: CollationCaseFirst.Off |
|
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: CollationStrength Default: CollationStrength.Tertiary |
|
| (Optional) Specifies whether the driver compares numeric strings as numbers. If this argument is true , the driver compares numeric strings as numbers.
For example, when comparing the strings "10" and "2", the driver treats the values
as 10 and 2, and finds 10 to be greater.If this argument is false or excluded, the driver compares numeric strings
as strings. For example, when comparing the strings "10" and "2", the driver
compares one character at a time. Because "1" is less than "2", the driver finds
"10" to be less than "2".For more information, see Collation Restrictions
in the MongoDB Server manual. Data Type: boolean Default: false |
|
| (Optional) Specifies whether the driver considers whitespace and punctuation as base
characters for purposes of comparison. Data Type: CollationAlternate Default: CollationAlternate.NonIgnorable (spaces and punctuation are
considered base characters) |
|
| (Optional) Specifies which characters the driver considers ignorable when
the alternate argument is CollationAlternate.Shifted .Data Type: CollationMaxVariable Default: CollationMaxVariable.Punctuation (the driver ignores punctuation
and spaces) |
|
| (Optional) Specifies whether the driver normalizes text as needed. Most text doesn't require normalization. For more information about
normalization, see the ICU documentation. Data Type: boolean Default: false |
|
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: boolean Default: false |
|
Para obter mais informações sobre agrupamento, consulte a página Agrupamento no manual do MongoDB Server .
Contagem estimada
Para estimar o número total de documentos em sua coleção, use o método EstimatedDocumentCount()
.
Observação
O método EstimatedDocumentCount()
é mais eficiente do que o método CountDocuments()
, pois usa os metadados da collection em vez de fazer a varredura de toda a collection.
Modificar comportamento
Você pode modificar o comportamento do EstimatedDocumentCount()
passando um tipo de EstimatedDocumentCountOptions
como um parâmetro. Se você não especificar nenhuma opção, o driver usará valores padrão.
Você pode definir as seguintes propriedades em um objeto EstimatedDocumentCountOptions
:
Propriedade | Descrição |
---|---|
| The maximum amount of time that the query can run on the server. Default: null |
Exemplo
O exemplo a seguir estima o número de documentos na coleção students
:
var count = _myColl.EstimatedDocumentCount(); Console.WriteLine("Estimated number of documents in the students collection: " + count);
Estimated number of documents in the students collection: 6
Agregação
Você pode utilizar o método de construtor Count()
para contar o número de documentos em uma aggregation pipeline.
Exemplo
O exemplo a seguir executa as seguintes ações:
Especifica um estágio de correspondência para encontrar documentos com um valor
FinalGrade
maior que80
Conta o número de documentos que correspondem aos critérios
var filter = Builders<Student> .Filter.Gt(s => s.FinalGrade, 80); var result = _myColl.Aggregate().Match(filter).Count(); Console.WriteLine("Number of documents with a final grade more than 80: " + result.First().Count);
Number of documents with a final grade more than 80: 4
Informações adicionais
Para saber mais sobre as operações mencionadas, consulte os seguintes guias:
Documentação da API
Para saber mais sobre qualquer um dos métodos ou tipos discutidos neste guia, consulte a seguinte documentação da API: