How to Count the Number of Documents in a MongoDB Collection
To count the number of documents in a MongoDB collection using commands in the MongoDB shell, you can use the count() method provided by the shell. Here's an example:
- Open the MongoDB shell by running the mongo command in your terminal.
- Switch to the database that contains the collection you want to count using the use command. For example, use myDatabase.
- Use the db.<collection>.count() command to count the number of documents in the collection. Replace <collection> with the name of your collection. For example, db.myCollection.count().
Here's an example of the full sequence of commands to count the number of documents in a collection called "myCollection" in a database called "myDatabase":
mongo // start the MongoDB shell
use myDatabase // switch to the myDatabase database
db.myCollection.count() //count the number of documents in the myCollection collection
After running the last command, the shell will return a number indicating the total number of documents in the collection.