MongoDB的 - 通过列表
问题描述:
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将是不同的,每个等级
感谢我的输出的例子!
答
我假设你的代码做了这样的事情:
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 does 不保证修改集中元素的特定顺序。
+0
谢谢,它工作很好。抱歉,我放了别的东西,而不是我的代码,我编辑了它。 – Dror
那么你运行的代码是什么? –
可能重复[如何从数组中删除重复项?](https://stackoverflow.com/questions/9862255/how-to-remove-duplicate-entries-from-an-array) – Veeram