2014-01-28 45 views
0

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

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 ... 

这可能吗?

回答

1

不,您不能将结果从一个聚合传递到第二个聚合。虽然您可以通过文档_id的列表来筛选使用$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 
+0

感谢您的信息!是的,我上面的例子是非常基本的,所以我会对数据进行一些手动操作,但我希望可以继续使用干净的聚合管道语法来处理一些棘手的问题。 –