How to use Distinct in Mongodb with example

In this blog post, we will explore working with MongoDB Distinct Operation. After reading this article, you all have a very clear understanding of how MongoDB distinct operations work and how to use it effectively.

Also Read: Best MongoDB Interview Questions

MongoDB Distinct

What is MongoDB Distinct?

MongoDB Distinct is to find the distinct values i.e the unique values for a specified field across a single collection or view and returns the results in the form of an array.

A prime example of this is the case that when we need to find a distinct username from the student collection in MongoDB. The MongoDB Distinct is one of several most used operators provided by the MongoDB directly out of the box.

In this tutorial, we will first explore the basics of using MongoDB distinct by working with the distinct operators and their example code. MongoDB distinct can be used in various ways according to the needs of the user and the situation in which it is needed.

Meanwhile, If you are not following along and are just interested in information on MongoDB Distinct Operator, you can visit the below sections.

What is the syntax of Mongodb Distinct?

Here is the given syntax of MongoDB distinct operation.

db.collection.distinct(field, query, options)

The Distinct method can take 3 arguments which are as follows:

  1. Field – the name of the field, of which you want the distinct values.
  2. Query – A query that specifies the documents from which to retrieve the distinct values.
  3. Options – Optional. A document that specifies the options.

Examples of MongoDB Distinct

{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }

db.inventory.distinct( "dept" ) // Distinct Query

[ "A", "B" ] // Output

So this is all about how to use Distinct in MongoDB. Thanks for reading!

Leave a Comment