Get distinct values in array when distinct too big, 16mb cap

Viewed 147

I have the following documents in the products collection:

{
   "_id": "1",
   "labels": ["item-1", "item-2"]
},
{
   "_id": "2",
   "labels": ["item-1", "item-4"]
}

I am trying to get a list of all distinct values in the "labels" array of each document:

item-1
item-2
item-4

I am getting the error "errmsg" : "distinct too big, 16mb cap" when I run the distinct command:

db.products.distinct("labels")

I tried running an aggregate function but i'm getting combination of labels and not the list of distinct labels. How can I make the $group return a distinct list of individual labels and not the distinct combination of labels?

[
  {
     $group: {
        _id : "$labels"
     }
  }
]
1 Answers

You can use unwind and group

db.collection.aggregate([
  { "$unwind": "$labels" },
  {
    "$group": {
      "_id": null,
      "labels": { "$addToSet": "$labels" }
    }
  }
])

Working Mongo playground

Related