Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$groupgroups all documents together using_id: null -
$addToSetcollects unique values from the Subject field into an array -
$projectexcludes 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.
Advertisements
