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
MongoDB GroupBy to set status
To group documents by status and categorize them into different arrays in MongoDB, use the aggregate() method with $group, $cond, and $push operators to conditionally separate documents based on their status values.
Syntax
db.collection.aggregate([
{
$group: {
_id: null,
"categoryName": {
$push: {
$cond: [
{ $eq: ["$fieldName", value] },
{ _id: "$_id", fieldName: "$fieldName" },
false
]
}
}
}
},
{
$project: {
_id: 0,
"categoryName": {
$setDifference: ["$categoryName", [false]]
}
}
}
]);
Sample Data
db.demo149.insertMany([
{ "Status": 40 },
{ "Status": 40 },
{ "Status": 50 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e350386fdf09dd6d08539c4"),
ObjectId("5e350388fdf09dd6d08539c5"),
ObjectId("5e35038afdf09dd6d08539c6")
]
}
Display all documents from the collection ?
db.demo149.find();
{ "_id": ObjectId("5e350386fdf09dd6d08539c4"), "Status": 40 }
{ "_id": ObjectId("5e350388fdf09dd6d08539c5"), "Status": 40 }
{ "_id": ObjectId("5e35038afdf09dd6d08539c6"), "Status": 50 }
Example: Group by Status and Set Categories
Group documents by status values and categorize them into "done" (Status=40) and "notdone" (Status=50) arrays ?
db.demo149.aggregate([
{
"$group": {
"_id": null,
"done": {
"$push": {
"$cond": [
{ "$eq": ["$Status", 40] },
{ "_id": "$_id", "Status": "$Status" },
false
]
}
},
"notdone": {
"$push": {
"$cond": [
{ "$eq": ["$Status", 50] },
{ "_id": "$_id", "Status": "$Status" },
false
]
}
}
}
},
{
"$project": {
"_id": 0,
"done": {
"$setDifference": ["$done", [false]]
},
"notdone": {
"$setDifference": ["$notdone", [false]]
}
}
}
]);
{
"done": [
{ "_id": ObjectId("5e350386fdf09dd6d08539c4"), "Status": 40 },
{ "_id": ObjectId("5e350388fdf09dd6d08539c5"), "Status": 40 }
],
"notdone": [
{ "_id": ObjectId("5e35038afdf09dd6d08539c6"), "Status": 50 }
]
}
How It Works
-
$groupwith_id: nullgroups all documents into a single group -
$condconditionally pushes documents into arrays based on status values -
$setDifferenceremoves false values from arrays, keeping only matched documents -
$projectshapes the final output and excludes the_idfield
Conclusion
Use MongoDB's aggregation pipeline with $group, $cond, and $setDifference operators to group documents by status values and organize them into categorized arrays. This approach provides flexible document categorization based on field conditions.
Advertisements
