2

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":"[email protected]",
  "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" : "[email protected]" } }, 
{ "$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 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You only need change $push to $addToSet.

A set not contains repeat values so it works.

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

Mongo Playground example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.