【问题标题】:MongoDB aggregate arrayMongoDB聚合数组
【发布时间】:2012-11-05 22:32:54
【问题描述】:

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

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

我怎样才能获得所有集合的toppings 的列表?

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

谢谢!

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

【问题讨论】:

  • 您是否只是尝试遍历 toppings 数组? $cursor = $collection->find(toppings); $array = iterator_to_array($cursor);

标签: mongodb pymongo


【解决方案1】:

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

【讨论】:

  • 在相关的注释上——你知道我如何在数据库层计算它(不在返回列表上调用len)吗?
  • db.collection.distinct('toppings').length 返回长度。这是在 mongodb 控制台中。看起来 pymongo 没有内置的。
【解决方案2】:

您可以为此使用distinct 查询:

db.coll.distinct('toppings')

【讨论】:

    【解决方案3】:

    distinct 将适用于有限数量的独特项目(

    如果不止于此,您必须使用 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

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

    您的配料项将是您的输出集合的 _id,而值将表示每个颗粒配料的计数

    【讨论】:

      猜你喜欢
      • 2014-12-01
      • 1970-01-01
      • 2021-04-28
      • 2021-06-21
      • 2019-09-28
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多