Navigation
This version of the manual is no longer supported.

count

count

The count command counts the number of documents in a collection. The command returns a document that contains the count as well as the command status. The count command takes the following prototype form:

{ count: <collection>, query: <query>, limit: <limit>, skip: <skip> }

The command fields are as follows:

Fields:
  • count (String) – The name of the collection to count.
  • query (document) – Optional. Specifies the selection query to determine which documents in the collection to count.
  • limit (integer) – Optional. Specifies the limit for the documents matching the selection query.
  • skip (integer) – Optional. Specifies the number of matching documents to skip.

Consider the following examples of the count command:

  • Count the number of all documents in the orders collection:

    db.runCommand( { count: 'orders' } )
    

    In the result, the n, which represents the count, is 26 and the command status ok is 1:

    { "n" : 26, "ok" : 1 }
    
  • Count the number of the documents in the orders collection with the field ord_dt greater than new Date('01/01/2012'):

    db.runCommand( { count:'orders',
                     query: { ord_dt: { $gt: new Date('01/01/2012') } }
                   } )
    

    In the result, the n, which represents the count, is 13 and the command status ok is 1:

    { "n" : 13, "ok" : 1 }
    
  • Count the number of the documents in the orders collection with the field ord_dt greater than new Date('01/01/2012') skipping the first 10 matching records:

    db.runCommand( { count:'orders',
                     query: { ord_dt: { $gt: new Date('01/01/2012') } },
                     skip: 10 }  )
    

    In the result, the n, which represents the count, is 3 and the command status ok is 1:

    { "n" : 3, "ok" : 1 }
    

Note

MongoDB also provides the cursor.count() method and the shell wrapper db.collection.count() method.