Home MongoDB How to use the distinct count query in MongoDB

How to use the distinct count query in MongoDB

distinct count query in mongodb

Displaying a specific number of documents in a particular collection is one of the retrieval queries. Use the distinct count query when you have hundreds of documents in a collection and want to know the total number of distinct documents in that collection.

In today’s MongoDB tutorial series post, we shall discuss the fundamental notion of distinct count queries and their use in MongoDB.

Utilizing the distinct count query in MongoDB

The main reason for counting different documents is to eliminate duplication, which can waste time and resources when querying. The syntax of the distinct method is as follows:

db.collection-name.distinct("<field>", "<query>", "<options>").length

From the above command, the separate fields are retrieved by using the distinct() function, and the “.length” variable counts the number of fields provided by the distinct() method.

Prerequisites

A few MongoDB-based Ubuntu instances must be available to get to the practice session. For example, you must verify you have the following prerequisites:

  1. Database: Your Ubuntu must have a valid MongoDB database. For example, we’re using a database called “fosslinux.”
  2. Collection: A collection is required after the database and must be connected with your database. In this tutorial, the collection name is “fosslinuxtuts.”

The following section depicts how to use the distinct count function in MongoDB.

The distinct count method in use

Before we start with some samples, let’s look at the items in our “fosslinuxtuts” collection. To do so, execute the following line of code:

db.fosslinuxtuts.find().pretty()
check items in our collection

Check items in our collection

We shall use the content in our collection to try out some examples that will aid us in understanding how to use the distinct count query in MongoDB.

Note: If you have not created any inputs on your collection, execute this line of code to create a new collection:

db.fosslinuxtuts.insertMany([
{Name: "Abraham", Designation: ["Author", "Junior"], WriterCode: 01}, 
{Name: "Emmanuel", Designation: ["Author", "Junior"], WriterCode: 02}, 
{Name: "Hend", Designation: ["Author", "Junior"], WriterCode: 03}
])
insert documents in a collection

Insert documents in a collection

Once you have items in your collection, you can proceed and try out the examples provided herein:

Example 1: Retrieving the distinct field names in the “Name” field

The distinct() function is called to the “Name” field in this example, and it returns the names of separate fields in the “fosslinuxtuts” collection. To do this, we ran the following command in MongoDB Shell.

db.fosslinuxtuts.distinct("Name")
display names field

Display names field

From the output above, it is evident that the “distinct()” method displays the names of the distinct fields specified in the command.

Example 2: Extracting and Counting the number of distinct values in the “Name” field

Using the previous example, we will use the below command to count the number of unique fields in the “Name” fields of the “fosslinuxtuts” collection.

db.fosslinuxtuts.distinct("Name").length
display name field count

Display name field count

Example 3: Counting the number of distinct values in an array field

The “Designation” field in the “fosslinuxtuts” collection is an array containing the author’s designation and role. For instance, the command below will count the number of distinct values:

db.fosslinuxtuts.distinct("Designation").length
count the number of distinct values

Count the number of distinct values

Example 4: Using the distinct() method to query a condition

Here I will illustrate how to use the distinct() method to query a condition, and in such a circumstance, only the distinct values are returned, and they must match the query condition. For example, the following command will return the count of the distinct values present in the “Designation” field, and it must meet the query condition provided, which in this case is [Name: “WriterCode”]

db.fosslinuxtuts.distinct("Designation", {Name: "WriterCode"}).length
count the number of distinct values

Query a condition

From the above output, it is evident that there are “2” distinct fields within the “Designation” field in which the “Designation” matches the “Junior” provided.

Example 5: Extracting and Counting the number of distinct values in a numeric field

The distinct approach is also applicable to MongoDB’s numerical data types. Similar to the “fosslinuxtuts” collection, the “WriterCode” field contains values that are of the “Integer” datatype. The command below counts how many different values there are in the “WriterCode” field.

db.fosslinuxtuts.distinct("WriterCode").length
fields containing integer data types

Fields containing integer data types

That’s it about using a distinct count query in your MongoDB

Conclusion

This guide has comprehensively covered how to use the distinct query method in MongoDB. In addition, it has provided examples that will help you quickly grasp the concept of using the distinct query method. MongoDB, like any other database, plays a crucial role in the retrieval of documents, and it uses the distinct() method to retrieve the distinct values of a provided field. I hope you found this tutorial guide helpful, and if yes, feel free to give it a thumbs up.

You may also like

Leave a Comment

fl_logo_v3_footer

FOSS Linux is a leading resource for Linux enthusiasts and professionals alike. With a focus on providing the best Linux tutorials, open-source apps, news, and reviews, FOSS Linux is the go-to source for all things Linux. 


Whether you’re a beginner or an experienced user, FOSS Linux has something for everyone.

Follow Us

Subscribe

©2016-2023 FOSS LINUX

A PART OF VIBRANT LEAF MEDIA COMPANY

ALL RIGHTS RESERVED.

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.