Dror
Dror

Reputation: 25

MongoDB - remove duplicate values in group by list

Mongodb Collection -:

    {
"_id" : ObjectId("59b0fdea8711111"),
"address" : {
    "building" : "123",
},
"borough" : "Manhattan",
"grades" : [ 
    {
        "grade" : "A",
        "score" : 8
    }, 
    {
        "grade" : "B",
        "score" : 23
    }, 
    {
        "grade" : "A",
        "score" : 12
    }, 
],
"name" : "Glorious Food",
"restaurant_id" : "30112340"

}

I need to group all by grade, and then to have a list of all the names with that grade. When I run my code, i got it but I had duplicates values, as you can see than entity have 3 grades, 2 of them with A grade so that entity will appear twice in my list this is my code:

    db.getCollection('restaurants').aggregate([
{$project:{
    "borough":1,
    "grades.grade":1,
    "name":1
    }},                                    
{$match:{"borough":"Manhattan"}},
{$unwind:"$grades"},
{$group:{
    "_id":"$grades",
    name:{$push: {restname:"$name"}}}},
 {$sort:{"_id":1}}


])

and here is an example of my output

    {
"_id" : {
    "grade" : "A"
},
"name" : [ 
    {
        "restname" : "Glorious Food"
    }, 
    {
        "restname" : "Glorious Food"
    {
        "restname" : "1 East 66Th Street Kitchen"
    }, 

bottom line, I want the restname will be distinct for each grade

Thanks!

Upvotes: 1

Views: 2545

Answers (1)

Alex P.
Alex P.

Reputation: 3171

I assume your code did something like this:

db.collection.aggregate([
{ $unwind: "$grades"},
{
  $group: {
    _id: { grade: "$grades.grade"},
    name: { $push: { restname: "$name"}}
  }
}
])

what you need to use is $addToSet instead of $push:

db.collection.aggregate([
{ $unwind: "$grades"},
{
  $group: {
    _id: { grade: "$grades.grade"},
    name: { $addToSet: { restname: "$name"}}
  }
}
])

Here the behavior of $addToSet

$addToSet only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements. $addToSet does not guarantee a particular ordering of elements in the modified set.

Upvotes: 4

Related Questions