'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]

  1. $group - Group by null and with $addToSet to add name to names array without duplicates.

  2. $project - Decorate the output documents. With $size to count the size of the names array.

db.collection.aggregate([
  {
    $group: {
      _id: null,
      names: {
        $addToSet: "$name"
      }
    }
  },
  {
    $project: {
      count: {
        $size: "$names"
      }
    }
  }
])

Sample Mongo Playground

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