Muirik
Muirik

Reputation: 6289

Count Unique Values in MongoDB

In the $facet stage of my mongoDB pipeline, because some records reference the same "customer.id", I need to count based on unique occurrences of "customer.id". I have tried this:

"totalCustomers" : [ { $group : { "$customer.id" : { $sum: 1 } } } ]

... but end up with the error: "The field name '$customer' cannot be an operator name".

I also tried this:

"totalCustomers" : [  { "$group" : { "_id" : "$customer.id", "count" : { "$sum" : 1 }}}   ]

... which doesn't error out, but that gives me all the records, rather than the numerical count of all those records.

What is the syntax for doing a count on every unique "$customer.id" from my data set? My understanding is that I need to use $sum within either a $group or $project stage, but am unclear as to the specifics of what this is supposed to look like.

To clarify further, if my data structure looks like this:

[
  {
  id: '111',
  someProp: <value>,
  customer: { id: '222' } 
  },
  {
  id: '112',
  someProp: <value>,
  customer: { id: '222' } 
  }
]

... I should end up with "totalCustomers: 1".

Upvotes: 2

Views: 316

Answers (1)

Radosław Miernik
Radosław Miernik

Reputation: 4094

You can do it within two steps:

[
    {$group: {_id: null, customerIds: {$addToSet: '$customer.id'}}},
    {$project: {uniqueCustomers: {$size: '$customerIds'}}}
]

This will create a set (technically an array without duplicates) with all customer.ids and get its size.

Upvotes: 3

Related Questions