'Count the number of item without duplicate in mongodb by node js
Here is my json
[
{
id:1,
name:'rakib'
},
{
id:2,
name:'sakib'
},
{
id:3,
name:'sakib'
},
{
id:4,
name:'akib'
}
]
In this, I want to count the number of names but not duplicate by node js in MongoDB My count will be: 3 ('rakib', 'sakib', 'akib')
Solution 1:[1]
$group- Group bynulland with$addToSetto addnametonamesarray without duplicates.$project- Decorate the output documents. With$sizeto count the size of thenamesarray.
db.collection.aggregate([
{
$group: {
_id: null,
names: {
$addToSet: "$name"
}
}
},
{
$project: {
count: {
$size: "$names"
}
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yong Shun |
