MongoDB – 使用聚合展开arrays并删除重复项

我使用MongoDB聚合框架展开一个数组,并且数组有重复,我需要进一步进行分组时忽略这些重复。

我怎样才能做到这一点?

你可以使用$ addToSet来做到这一点:

db.users.aggregate([ { $unwind: '$data' }, { $group: { _id: '$_id', data: { $addToSet: '$data' } } } ]); 

没有看到你的实际查询,很难给你更具体的答案。

你必须使用$ addToSet,但是首先你必须用_id分组,因为如果你不这样做,你会得到列表中每个元素的元素。

想像一下收集这样的文件的post:

 { body: "Lorem Ipsum...", tags: ["stuff", "lorem", "lorem"], author: "Enrique Coslado" } 

想象一下,你要计算每个作者最常用的标签。 你会做这样的聚合查询:

 db.posts.aggregate([ {$project: { author: "$author", tags: "$tags", post_id: "$_id" }}, {$unwind: "$tags"}, {$group: { _id: "$post_id", author: {$first: "$author"}, tags: {$addToSet: "$tags"} }}, {$unwind: "$tags"}, {$group: { _id: { author: "$author", tags: "$tags" }, count: {$sum: 1} }} ]) 

这样你会得到这样的文件:

 { _id: { author: "Enrique Coslado", tags: "lorem" }, count: 1 }