Overview
En esta guía podrás aprender cómo obtener un recuento preciso y estimado del número de documentos de su colección.
Datos de muestra
Los ejemplos de esta guía utilizan los siguientes documentos en una colección denominada
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 }
La siguiente clase Student modela los documentos en esta colección:
public class Student { public int Id { get; set; } public string Name { get; set; } public double FinalGrade { get; set; } }
Nota
Los documentos de la colección students utilizan la convención de nomenclatura camel case. En los ejemplos de esta guía, se utiliza un ConventionPack para deserializar los campos de la colección en notación Pascal y asignarlos a las propiedades de la clase Student.
Para obtener más información sobre la serialización personalizada, consulte Serialización personalizada.
Conteo preciso
Para contar el número de documentos que coinciden con su filtro de consulta, utilice el CountDocuments() método. Si pasa un filtro de consulta vacío, este método devuelve el número total de documentos de la colección.
Ejemplo
El siguiente ejemplo cuenta la cantidad de documentos donde el valor de finalGrade es 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 el comportamiento
Puede modificar el comportamiento de CountDocuments() pasando un tipo CountOptions como parámetro. Si no especifica ninguna opción, el controlador usa los valores predeterminados.
Puede establecer las siguientes propiedades en un objeto CountOptions:
Propiedad | Descripción |
|---|---|
| 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 |
Tip
Al usar CountDocuments() para devolver el número total de documentos de una colección, MongoDB realiza un escaneo de la colección. Puede evitarlo y mejorar el rendimiento de este método usando una sugerencia para aprovechar el índice integrado en el campo _id. Use esta técnica solo al llamar a CountDocuments() con un parámetro de consulta vacío.
var filter = Builders<Student>.Filter.Empty; CountOptions opts = new CountOptions(){Hint = "_id_"}; var count = collection.CountDocuments(filter, opts);
Intercalación
Para configurar la intercalación para tu operación, crea una instancia de la clase intercalación.
La siguiente tabla describe los parámetros que acepta el constructor Collation. También enumera la propiedad de clase correspondiente que se puede usar para leer el valor de cada configuración.
Parameter | Descripción | Propiedad de clase |
|---|---|---|
| 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: booleanDefault: 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: booleanDefault: 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: booleanDefault: false |
|
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: booleanDefault: false |
|
Más información sobre la intercalación en la página Intercalación en el manual de MongoDB Server.
Recuento estimado
Para estimar el número total de documentos en su colección, utilice el método EstimatedDocumentCount().
Nota
El método EstimatedDocumentCount() es más eficiente que el método CountDocuments() porque utiliza los metadatos de la colección en lugar de escanear toda la colección.
Modificar el comportamiento
Puede modificar el comportamiento de EstimatedDocumentCount() pasando un tipo EstimatedDocumentCountOptions como parámetro. Si no especifica ninguna opción, el controlador usa los valores predeterminados.
Puede establecer las siguientes propiedades en un objeto EstimatedDocumentCountOptions:
Propiedad | Descripción |
|---|---|
| The maximum amount of time that the query can run on the server. Default: null |
Ejemplo
El siguiente ejemplo estima la cantidad de documentos en la colección 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
Agregación
Puede utilizar el método de construcción Count() para contar la cantidad de documentos en una secuencia de agregación.
Ejemplo
El siguiente ejemplo realiza las siguientes acciones:
Especifica una etapa de coincidencia para encontrar documentos con un valor
FinalGrademayor que80Cuenta el número de documentos que coinciden con los criterios
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
Información Adicional
Para obtener más información sobre las operaciones mencionadas, consulte las siguientes guías:
Documentación de la API
Para obtener más información sobre cualquiera de los métodos o tipos discutidos en esta guía, consultar la siguiente documentación de la API: