MongoDB group by array subfield

Viewed 127

Hello I am new to mongoDB, please I hope you can help me with this question.

My collection will look like this:

{
  "_id": { "$oid": "5f1fd47..." },
  "email":"c@c.com",
  "materials": [
    {
       "_id": { "$oid": "5f1fda2..." },
       "title": "MDF 18mm Blanco",
       "id": "mdf18blanco",
       "thickness": "18",
       "family": "MDF",
       "color": ""
    }, ...
    //others materials with different family
  ],
}

I did an aggregate like this:

{ "$match" : { "email" : "c@c.com" } }, 
{ "$unwind" : "$materials" }, 
{ "$group" : { "_id" : "$_id", "list" : { "$push" : "$materials.family" } } } 

and I return this:

{ 
    "_id" : ObjectId("5f1fd47d502e00051c673dd1"), 
    "list" : [
        "MDF", 
        "MDF", 
        "MDF", 
        "Melamina", 
        "Melamina", 
        "Melamina", 
        "Melamina", 
        "MDF", 
        "Melamina", 
        "Aglomerado", 
        "Aglomerado"
    ]
}

but i need get this

 { 
    "_id" : ObjectId("5f1fd47d502e00051c673dd1"), 
    "list" : [
        "MDF", 
        "Melamina", 
        "Aglomerado"
    ]
}

I hope you understand my question and can help me, thank you very much.

2 Answers

All you need to do is use $addToSet instead of $push in your group stage:

{ "$group" : { "_id" : "$_id", "list" : { "$addToSet" : "$materials.family" } } } 

One thing to note is that $addToSet does not guarantee a specific order as opposed to $push in case it matters to you.

You only need change $push to $addToSet.

A set not contains repeat values so it works.

db.collection.aggregate([
  {
    "$match": {
      "email": "c@c.com"
    }
  },
  {
    "$unwind": "$materials"
  },
  {
    "$group": {
      "_id": "$_id",
      "list": {
        "$addToSet": "$materials.family"
      }
    }
  }
])

Mongo Playground example

Related