0

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

  • 1
    Does this answer your question? [mongodb count num of distinct values per field/key](https://stackoverflow.com/questions/14924495/mongodb-count-num-of-distinct-values-per-field-key) – hoangdv May 08 '22 at 03:42

1 Answers1

0
  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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46