2017-12-27 2192 views
0

MongoDB的集合中刪除組重複的值 - :MongoDB的 - 通過列表

{ 
"_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" 

}

我需要把所有的等級,然後將所有與該等級的名稱列表。 當我運行我的代碼,我得到它,但我不得不重複的值,你可以看到比實體有3個等級,其中2例A級,這樣的實體將在我的名單 兩次出現,這是我的代碼:

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}} 


]) 

,這裏是

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

底線,我想restname將是不同的,每個等級

感謝我的輸出的例子!

+0

那麼你運行的代碼是什麼? –

+0

可能重複[如何從數組中刪除重複項?](https://stackoverflow.com/questions/9862255/how-to-remove-duplicate-entries-from-an-array) – Veeram

回答

0

我假設你的代碼做了這樣的事情:

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

你需要使用的是$addToSet而不是$push

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

這裏$addToSet

$行爲addToSet只確保沒有將重複項添加到 集並不會影響現有的重複元素。 $ addToSet does 不保證修改集中元素的特定順序。

+0

謝謝,它工作很好。抱歉,我放了別的東西,而不是我的代碼,我編輯了它。 – Dror