Counting unique elements in a subdocument array

Viewed 1040

I have an subdocument that has an array of names. I want the number of unique names in the collection. A document looks like:

{name: "salesman",
 people: [{name: "Joe"}, {name: "Brian"}]}

I have run:

db.jobs.aggregate([
  {$unwind: "$job.people"},
  {$group: {_id: "$job.people.name"}},
  {$group: {_id: null, total: {$sum: 1}}}
]);

This seems to work, but since there are a lot of unique names in the DB I don't have a very good way of verifying that it is correct, so I thought I would check here.

Is there a preferred method for counting the number of unique items in a subdocument array?

1 Answers
Related