我想获取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 ...
这可能吗?
答案 0 :(得分: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