【问题标题】:Perform additional aggregation on an existing Mongoose aggregate result对现有 Mongoose 聚合结果执行附加聚合
【发布时间】:2014-02-19 02:41:39
【问题描述】:

我想获取 Mongoose Model.aggregate 命令的结果并对其执行其他聚合方法。这个想法是我可以只查询一次数据库,聚合到某个点,然后对这些结果执行其他聚合方法,而无需再次重新查询数据库。 (下面的代码是 Coffeescript)

firstAggregation = [
    {
      $geoNear: {
        near:
          type: "Point"
          coordinates: geo
        includeLocs: "geo"
        distanceField: "distance"
        maxDistance: distance
        spherical: true
        uniqueDocs: true
      }
    },
    {
      $match: { "active" : true }
    }
  ]

secondAggregation = firstAggregation.concat [
        {
          $unwind: "$offers"
        },
        {
          $group: {
            _id: "$offers"
          }
        }
      ]

app.MyModel.aggregate firstAggregation, (err, results) ->

  # ... do something with the first results ...

  # **** apply secondAggregation here! ****
  # the below doesn't work, but its what I want to achieve

  results.aggregate secondAggregation, (err, secondResults) ->
    # ... do something with the second results without having requeried the DB ...

这可能吗?

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    不,您不能将结果从一个聚合传递到第二个聚合。虽然您可以传递一个文档列表_ids 以使用$in 进行过滤,但除此之外,您真的无能为力。

    { $match : { _id : { $in: [ /* list of _ids */] } } } 
    

    尽管考虑到当前 v2.4 对聚合框架结果的限制(结果上限为 16MB),但您可以执行与您可能希望在客户端内存中的数据库上执行的操作类似的逻辑(在本例中为 NodeJS) .

    在您问题的上述示例中,它看起来只是例如尝试为字段 offers 的值数组查找所有不同值?

    offerNames = {}
    for result in results
        for offer in result.offers
            offerNames[i] = (offerNames[i] or 0) + 1
    
    for name, value of offerNames
        console.log name + " = " + value
    

    【讨论】:

    • 感谢您的信息!是的,我上面的示例非常基本,所以我将尝试对数据进行一些手动操作,但我希望可以继续使用聚合管道的简洁语法来解决一些更棘手的问题。
    猜你喜欢
    • 2014-12-24
    • 2015-04-28
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2018-08-01
    相关资源
    最近更新 更多