Skip to content

Commit

Permalink
Add group by to MongoDB
Browse files Browse the repository at this point in the history
  • Loading branch information
kasramp committed Jun 19, 2023
1 parent cba95f9 commit 6963070
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion database/mongodb.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: MongoDB
category: Database
layout: 2017/sheet
updated: 2023-05-22
updated: 2023-06-20
keywords:
- "mongodb"
- "mongo"
Expand Down Expand Up @@ -95,3 +95,44 @@ Should produce an output like this:
}
]
```

### Group by (find duplicate by a key)

```json
db.COLLECTION_NAME.aggregate([
{
$group: {
_id: "$FIELD_NAME",
count: { $sum: 1 },
duplicates: { $addToSet: "$_id" }
}
},
{
$match: {
count: { $gt: 1 }
}
}
], { allowDiskUse: true })
```

### Count group by

```json
db.COLLECTION_NAME.aggregate([
{
$group: {
_id: "$FIELD_NAME",
count: { $sum: 1 },
duplicates: { $addToSet: "$_id" }
}
},
{
$match: {
count: { $gt: 1 }
}
},
{
$count: "total"
}
], { allowDiskUse: true })
```

0 comments on commit 6963070

Please sign in to comment.