Cara menggunakan node mongodb distinct

In this MongoDB tutorial, we will understand distinct query in MongoDB. We will cover this topic with different operations and examples. Additionally, we will also discuss the following topics:

  • Distinct query in MongoDB
  • Distinct query in MongoDB example
  • Distinct query in MongoDB with condition
  • Distinct query in MongoDB nested array
  • Distinct query in MongoDB match
  • Distinct query in MongoDB multiple fields
  • Distinct query in MongoDB greater than
  • Distinct query in MongoDB index
  • Distinct query in aggregate MongoDB
  • Distinct query in MongoDB limit
  • Distinct count query in MongoDB
  • Distinct query in MongoDB compass
  • Distinct query in MongoDB using Python

Table of Contents

Distinct query in MongoDB

MongoDB finds the distinct values for a defined field over a single collection. The distinct method will return a document that contains an array of the distinct values.

The results document also contains an embedded document with query statistics and the query plan.

Syntax:

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

The command contains the following fields:

parameterTypeDescriptionfieldstringThe field name for which you want to return distinct values.querydocumentA query that specifies the documents from which to retrieve the distinct values.optionsdocumentOptional, A document that specifies the options.

Note, you will the aggregation pipeline to retrieve distinct values using the $group operator.

Distinct query in MongoDB example

In this topic, you will learn to find the distinct values for a given field across a single collection and return the result in an array.

You will more understand this with the help of an example.

Example:

The following documents were inserted into the students’ collection.

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])

After that, we will apply the below query to return the distinct name (fname) of all the students present in the collection:

db.student.distinct("fname")

Here, the distinct() method

  • Return all the fields of the fname column.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB example

  • Return all the distinct fields from an array field
db.student.distinct("courses")

Here, the distinct() method returns the value of the courses field.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB

We have successfully retrieved the distinct value from the collection.

Also, check: MongoDB Auto Increment ID

Distinct query in MongoDB with condition

Sometimes we have to apply the condition using the distinct method to find a particular document. So, In this topic, you will learn to apply the distinct query with conditions. Now, You will more understand with the help of an example.

Example:

The following documents were inserted into the inventory collection.

db.inventory.insertMany([
{ "_id": 1, "dept": "A", "item": { "sku": "101", "color": "red" }, "sizes": [ "S", "M" ] },
{ "_id": 2, "dept": "A", "item": { "sku": "102", "color": "blue" }, "sizes": [ "M", "L" ] },
{ "_id": 3, "dept": "B", "item": { "sku": "103", "color": "blue" }, "sizes": "S" },
{ "_id": 4, "dept": "A", "item": { "sku": "104", "color": "black" }, "sizes": [ "S" ] }
])

We will apply the below query to return distinct fields in MongoDB with conditions.

db.inventory.distinct( "item.sku", { dept: "A" } )

Here, the distinct() method will return the distinct values for the field sku, embedded in the item field, from all documents in the inventory collection.

The method returns the following array of distinct sku values:

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB with condition

Read: MongoDB remove a field from the document

Distinct query in MongoDB nested array

In this topic, you will know how to retrieve nested array documents by using the distinct() method. A nested array in JavaScript is described as an array (Outer array) within another array (inner array). An array can hold one or more inner arrays.

These nested arrays (inner arrays) are under the scope of the outer array means we can access these inner array elements based on the outer array object name. Now, the below example will help you to understand more precisely.

Example:

The following documents were inserted into the article collection.

db.article.insert([
  {
        "_id" : 101,
        "name" : "test 1",
        "Comment" : [
                {
                        "name" : "comment test",
                        "Reply" : [
                                {
                                        "ip" : "192.168.2.1",
                                        "email" : "yyy"
                                },
                                {
                                        "ip" : "127.0.0.1",
                                        "email" : "zzz"
                                }
                        ]
                }
        ]
},
{
        "_id" : 102,
        "name" : "test 2",
        "Comment" : [
                {
                        "name" : "comment 2 test",
                        "Reply" : [
                                {
                                        "ip" : "192.168.1.1",
                                        "email" : "xxx"
                                },
                                {
                                        "ip" : "127.168.1.1",
                                        "email" : "xxx"
                                }
                        ]
                }
        ]
}
])

After that, we will apply the below query to find the distinct fields in MongoDB nested array.

db.article.distinct("Comment.Reply.ip",{"Comment.Reply.email" : "xxx"})

Here, we have used the distinct() method and retrieved the ip from the nested array field “Comment.Reply.email” where the email is xxx.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB nested array

We have successfully retrieved the distinct fields from nested array documents in MongoDB.

Read: Create index in MongoDB

Distinct query in MongoDB match

In this topic, you will learn to find the distinct fields that match the query in MongoDB. You will more understand with the help of an example.

Example:

The following documents were inserted into the details collection.

db.details.insertMany([
 {
         "name" : "John",
         "age" : 21,
         "location" : "New York"
 },
 {
         "name" : "Sam",
         "age" : 25,
         "location" : "USA"
 },
 {
         "name" : "Lisa",
         "age" : 23,
         "location" : "Chicago"
 },
 {
         "name" : "Ron",
         "age" : 26,
         "location" : "New Zealand"
 },
 {
         "name" : "Mark",
         "age" : 29,
         "location" : "Canada"
 }
 ])

Now, we will apply the below query to the collection to find the match field using the distinct method.

db.details.distinct( "location", {"name": "John"} )

Here, we have used the distinct() method and retrieved the match fields location where the name is john.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB match

We have successfully retrieved the match field by using the distinct method.

Read: Missing before statement MongoDB

Distinct query in MongoDB multiple fields

In this topic, we will learn to perform the distinct method on multiple fields in MongoDB. Now, the $group operator along with the aggregation framework is used to perform distinct on multiple fields. The below example will help you to understand more precisely.

Example:

The following documents were inserted into the address collection.

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])
0

Now, the below query will display all the documents from a collection with the help of the find() method.

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])
1

This will produce the following output:

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct on multiple fields in MongoDB

We can not operate by using a distinct method so here we will use the aggregation operation and retrieve the multiple fields. Now, the following query will perform distinct on multiple fields in MongoDB:

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])
2

Here, we have used the aggregate() method. In this, the $group stage is used to retrieve the distinct item values and the $addToSet operator is used to add a value to an array unless the value is already present.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB multiple fields

We have successfully retrieved all the fields of the collection by performing distinct on multiple fields.

Read: MongoDB two-phase commit

Distinct query in MongoDB greater than

The greater than operation can not perform in MongoDB by using the distinct() method. So, we will use the aggregation operation and use the $group stage to retrieve the distinct item values from the collection. The below example will help you to understand more precisely.

Example:

The following documents were inserted into the sales collection:

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])
3

After that, we will apply the below query to retrieve the distinct fields that are greater than:

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])
4

Here, we have used the aggregation operation groups documents by the item field and calculated the total sale amount per item, and returned only the items with a total sale amount greater than equal to 100.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB greater than

We have successfully retrieved the distinct fields where the calculated total sales amount is greater than 100.

Read: MongoDB shutting down with code 48

Distinct query in MongoDB index

In this topic, you will understand find the distinct fields using indexes in MongoDB. An index covers a query when:

  • In the query, all the fields are part of an index.
  • And, all the fields returned in the results are in the same index.

Advantage:

  • The advantage of the index, it contains all fields required by the query and return the results using only the index.
  • The index can be much faster than querying documents outside of an index.

Let’s understand the below example to understand the problem more precisely:

Example:

We will use the inventory collection that contains the following documents.

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])
5

The find() method will use to return the documents of the collection.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB using an index

Now, you have to create the indexes for all the fields so that they should be able to support distinct queries.

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])
6

We successfully created the indexes and check them by using the getIndexes() method.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB index

Now, we can easily return the distinct field by using the below query.

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])
7

This query will return all the distinct fields of the sizes column.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct fields in MongoDB using an index

We have successfully retrieved the distinct fields using an index.

Note that, The benefits of indexes, when we have a large dataset and we want to find out distinct fields on the time with the help of indexes we can easily retrieve the distinct documents fields.

Read: How to create the indexes in MongoDB?

Distinct query in aggregate MongoDB

In this topic, you will learn to find distinct fields using aggregation operations.

The $group stage is used by the aggregation process to get the separate item values from the collection. The following example will help you to understand the problem more precisely:

Example:

The following documents were inserted into the artists’ collection:

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])
8

Now, we will apply the below query to where groups input documents by the specified _id expression and for each distinct grouping, outputs a document and the _id field of each output document contains the unique group by value.

db.students.insertMany([
{
        "fname" : "Tom",
        "city" : "USA",
        "courses" : [
                "c#",
                "asp",
                "node"
        ]
},
{
        "fname" : "Harry",
        "city" : "New Zealand",
        "courses" : [
                "python",
                "asp",
                "node"
        ]
},
{
        "fname" : "Mikky",
        "city" : "United Kingdom",
        "courses" : [
                "python",
                "asp",
                "c++"
        ]
},
{
        "fname" : "Ron",
        "city" : "Australia",
        "courses" : [
                "python",
                "django",
                "node"
        ]
}
])
9

Here, In the aggregation operation, we have defined the $group stage that will retrieve the distinct item values (first_name) from the artists’ collection.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in aggregate MongoDB

We have successfully retrieved all the distinct fields using the aggregation operation.

Note:

The $group does not order its output documents.

Read: MongoDB find multiple conditions

Distinct query in MongoDB limit

In this topic, you will use the limit() method and retrieve the limited number of distinct records or documents that you want. The following example will help you to understand the problem more precisely.

Example:

In this example, we are using the same collection that we used in the previous topic. For reference check the below snapshot:

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB limit

After that, we will apply the below query to the collection and retrieve the limited number of distinct records or fields.

db.student.distinct("fname")
0

Here, In the aggregation operation, we have defined the $group stage that will retrieve the distinct item values (first_name) from the artists’ collection. And, the $limit operation returns only the first 3 documents.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB using limit

We have successfully retrieved the limit number of distinct fields using the aggregation operation.

Note: The $group does not order its output documents.

Distinct count query in MongoDB

In this topic, you will learn to count the distinct fields from the collection. MongoDB has a distinct command which returns an array of distinct values for a field and you can check the length of the array using the length command for a count.

Example:

The following documents were inserted into the car collection.

db.student.distinct("fname")
1

Now, we will apply the below query to count the number of distinct fields.

db.student.distinct("fname")
2

For reference see the execution of the code:

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct count query in MongoDB

We have successfully retrieved the length of the array of distinct values using the length command.

Read: MongoDB Update Documents

Distinct query in MongoDB compass

In this topic, you will learn to find the distinct fields using the MongoDB compass.

MongoDB Compass is a GUI (graphic user interface) to explore, analyze, and interact with the data stored in the MongoDB database without using queries.

Example:

In this example, we will find the distinct fields or records using the MongoDB compass.

You have to follow the below step to understand the example:

  • Open the MongoDB compass and connect with the server.
  • Select the database and collection in which you want to find out the distinct fields.
  • You can also create a new database and insert the documents into the collection.
  • Here, we are using the existing database and collection, test and inventory respectively.

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Select the database and collection

  • Now, we will use the aggregation operations and the $group stage that will retrieve the distinct item values from the collection.
db.student.distinct("fname")
3

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB compass

  • Check the bottom right side of the window for the output.

We have successfully retrieved all the distinct fields using MongoDB compass.

Read: MongoDB compare two fields

Distinct query in MongoDB using Python

In this topic, you will learn to find distinct fields or records of MongoDB using Python.

The PyMongo library includes the distinct() function that finds and returns the distinct values for a specified field across a single collection and returns the results in an array. Parameters: key: field name for which the distinct values need to be found.

Example:

The following example will help you to find out the distinct fields from the collection.

Code:

In the following code, we have imported the pymongo library to use MongoDB functionality in python.

  • Use the MongoClient class to make the connection with the server.
  • Created a database organization and collection car.
  • After that, we have inserted some documents into the collection using insert_many() method.
  • After that, we have used distinct() method to find the distinct fields of the mfdcountry column.
  • And, the print() function is use to return the result.
db.student.distinct("fname")
4

Check out the execution of code:

Cara menggunakan node mongodb distinct
Cara menggunakan node mongodb distinct
Distinct query in MongoDB using Python

We have successfully retrieved the list of distinct fields using python.

You may also like to read the following MongoDB tutorials.

  • How to change collection name in MongoDB
  • MongoDB find last inserted document
  • MongoDB remove an element from the array
  • MongoDB find string contains

So, In this tutorial, we have understood about Distinct queries in MongoDB. And, we have covered the different operations with examples. We have covered the list of the following topics:

  • Distinct query in MongoDB
  • Distinct query in MongoDB example
  • Distinct query in MongoDB with condition
  • Distinct query in MongoDB nested array
  • Distinct query in MongoDB match
  • Distinct query in MongoDB multiple fields
  • Distinct query in MongoDB greater than
  • Distinct query in MongoDB index
  • Distinct query in aggregate MongoDB
  • Distinct query in MongoDB limit
  • Distinct count query in MongoDB
  • Distinct query in MongoDB compass
  • Distinct query in MongoDB using Python

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.