fbpx

In MongoDB, the distinct command is used to find the distinct values for a specified field across all documents in a collection. This can be useful for finding unique values for a particular field, such as a list of unique names or email addresses.

To use the distinct command, you specify the field for which you want to find the distinct values and the name of the collection on which you want to run the command. For example, to find the distinct values for the “name” field in the “students” collection, you could use the following command:

				
					db.students.distinct("name")

				
			

The distinct command will return an array of the distinct values for the specified field. You can then use this array of values in further operations or queries.

For example, you could use the distinct command in combination with the count command to find the number of unique values for a particular field:

				
					db.students.distinct("name").length

				
			

The distinct command can also be used in conjunction with other query operators, such as $gt (greater than) and $lt (less than), to find distinct values that match a specific condition. For example, to find the distinct names of students who have a score greater than 80 on a test, you could use the following command:

				
					db.students.distinct("name", { score: { $gt: 80 } })

				
			

Overall, the distinct command is a powerful tool for finding and working with unique values in a MongoDB collection.

Share:

Facebook
Twitter
Pinterest
LinkedIn

Social Media

Most Popular

Get The Latest Updates

Subscribe To Our Weekly Newsletter

No spam, notifications only about new products, updates.

Categories