Count() & Remove() Functions in MongoDB with Example

MongoDB Count() Function

The concept of aggregation is to carry out a computation on the results which are returned in a query. For example, suppose you wanted to know what is the count of documents in a collection as per the query fired, then MongoDB provides the count() function.

Example of MongoDB Count() Function

Let’s look at an example of this.

db.Employee.count()

Code Explanation:

  • The above code executes the count function.

If the command is executed successfully, the following Output will be shown

Output:

Example of MongoDB Count() Function

The output clearly shows that 4 documents are there in the collection.

Performing Modifications

The other two classes of operations in MongoDB are the update and remove statements.

The update operations allow one to modify existing data, and the remove operations allow the deletion of data from a collection.

Remove() Function in MongoDB

In MongoDB, the db.collection.remove() method is used to remove documents from a collection. Either all of the documents can be removed from a collection or only those which matches a specific condition.

If you just issue the remove command, all of the documents will be removed from the collection.

Example of MongoDB Remove() Function

The following code example demonstrate how to remove a specific document from the collection.

db.Employee.remove({Employeeid:22})

Code Explanation:

  • The above code use the remove function and specifies the criteria which in this case is to remove the documents which have the Employee id as 22.

If the command is executed successfully, the following Output will be shown

Output:

Example of MongoDB Remove() Function

The output will show that 1 document was modified.