Projection result as an array of selected items in MongoDB?

Use the distinct() method to project results as an array of selected items in MongoDB. This method finds distinct values for a specified field across a collection and returns them in an array format.

Syntax

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

Sample Data

Let us first create a collection with documents ?

db.projectionListDemo.insertMany([
    {"_id": "1", "Subject": ["MongoDB", "MySQL", "Java"]},
    {"_id": "2", "Subject": ["MongoDB", "C", "C++"]},
    {"_id": "3", "Subject": ["Java", "Python"]}
]);
{
    "acknowledged": true,
    "insertedIds": ["1", "2", "3"]
}

Display all documents from the collection ?

db.projectionListDemo.find().pretty();
{ "_id" : "1", "Subject" : [ "MongoDB", "MySQL", "Java" ] }
{ "_id" : "2", "Subject" : [ "MongoDB", "C", "C++" ] }
{ "_id" : "3", "Subject" : [ "Java", "Python" ] }

Example: Get Array of Selected IDs

Get the _id values as an array for documents containing "MongoDB" in the Subject array ?

db.projectionListDemo.distinct('_id', {'Subject': 'MongoDB'});
[ "1", "2" ]

Example: Get Distinct Subject Values

Get all unique subjects across all documents ?

db.projectionListDemo.distinct('Subject');
[ "C", "C++", "Java", "MongoDB", "MySQL", "Python" ]

Conclusion

The distinct() method efficiently returns unique field values as an array. It accepts an optional query parameter to filter documents before extracting distinct values, making it ideal for projection-style operations.

Updated on: 2026-03-15T01:26:30+05:30

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements