1

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!

Dror
  • 25
  • 4
  • So what is the code that you run? – Alex P. Dec 27 '17 at 20:24
  • Possible duplicate of [How to remove duplicate entries from an array?](https://stackoverflow.com/questions/9862255/how-to-remove-duplicate-entries-from-an-array) – s7vr Dec 28 '17 at 02:18

1 Answers1

4

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.

Alex P.
  • 3,073
  • 3
  • 22
  • 33
  • Thanks, it work great. and sorry, i put something else instead of my code, i edited it. – Dror Dec 28 '17 at 07:26