Specify return format in MongoDB to return the values as an array?

To specify return format in MongoDB and return values as an array, use the aggregation pipeline with the $group stage and $addToSet operator to collect distinct values into an array.

Syntax

db.collection.aggregate([
    {
        "$group": {
            "_id": null,
            "fieldName": { "$addToSet": "$fieldPath" }
        }
    },
    {
        "$project": {
            "_id": 0,
            "fieldName": 1
        }
    }
]);

Sample Data

Let us first create a collection with documents −

db.specifyReturnFormatDemo.insertMany([
    {"Subject": "MongoDB"},
    {"Subject": "MySQL"},
    {"Subject": "SQL Server"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cefd364ef71edecf6a1f6c0"),
        ObjectId("5cefd369ef71edecf6a1f6c1"),
        ObjectId("5cefd36fef71edecf6a1f6c2")
    ]
}

Following is the query to display all documents from a collection −

db.specifyReturnFormatDemo.find();
{ "_id" : ObjectId("5cefd364ef71edecf6a1f6c0"), "Subject" : "MongoDB" }
{ "_id" : ObjectId("5cefd369ef71edecf6a1f6c1"), "Subject" : "MySQL" }
{ "_id" : ObjectId("5cefd36fef71edecf6a1f6c2"), "Subject" : "SQL Server" }

Example: Return Values as Array

Following is the query to specify return format and get all Subject values as an array −

db.specifyReturnFormatDemo.aggregate([
    {
        "$group": {
            "_id": null,
            "Subject": {
                "$addToSet": "$Subject"
            }
        }
    },
    {
        "$project": {
            "_id": 0,
            "Subject": 1
        }
    }
]);
{ "Subject" : [ "SQL Server", "MySQL", "MongoDB" ] }

How It Works

  • $group groups all documents together using _id: null
  • $addToSet collects unique values from the Subject field into an array
  • $project excludes the _id field and returns only the Subject array

Conclusion

Use aggregation with $group and $addToSet to transform individual document fields into a single array format. This approach is useful for collecting distinct values from multiple documents into one consolidated result.

Updated on: 2026-03-15T01:28:13+05:30

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements