2

假设我有一个 MongoDB 集合,其中包含以下文档——</p>

{
  "name": "Hawaiian",
  "toppings": ['cheese', 'ham', 'pineapple'],
}

我怎样才能得到所有收藏品的清单toppings

我假设我必须使用 MapReduce 或新的聚合框架(最好是 MapReduce,因为我不能使用新的聚合框架),但我不知道该怎么做。

谢谢!

编辑:而且,有没有办法在数据库级别计算不同浇头的数量?

4

3 回答 3

1

MongoDB 支持DISTINCT聚合。这应该可以解决问题。

于 2012-11-05T13:58:23.120 回答
1

您可以为此使用distinct查询:

db.coll.distinct('toppings')
于 2012-11-05T13:59:00.557 回答
1

distinct 将适用于有限数量的独特项目(<=50k?)

如果不止于此,您必须使用 mapreduce

fun_map ="""function () for (e in this.toppings) { emit (entities.toppings[e],1); } """

fun_reduce = """function (key, values) {var total = 0; for (var i = 0; i < values.length; i++) { total += values[i]; } return total;}""" then你打电话

collection.map_reduce(fun_map,fun_reduce,out={"replace":'your_outputcollection_name"}, full_response=True)

您的浇头项目将是您的输出集合的_id,而值将代表每个颗粒浇头的计数

于 2012-11-05T14:26:40.213 回答