gpt4 book ai didi

mongodb - Meteor 中的平均聚合查询

转载 作者:IT老高 更新时间:2023-10-28 13:08:12 27 4
gpt4 key购买 nike

好的,还是在我的玩具应用中,我想在一组车主的里程表上找出平均里程数。这在客户端上非常容易,但无法扩展。正确的?但是在服务器上,我并不完全明白如何完成它。

问题:

  1. 你如何在服务器上实现一些东西然后在客户端上使用它?
  2. 如何使用 mongo 的 $avg 聚合功能来发挥其优化的聚合功能?
  3. 或者替代 (2) 您如何在服务器上执行 map/reduce 并使其可供客户端使用?

@HubertOG 的建议是使用 Meteor.call,这是有道理的,我这样做了:

# Client side
Template.mileage.average_miles = ->
answer = null
Meteor.call "average_mileage", (error, result) ->
console.log "got average mileage result #{result}"
answer = result
console.log "but wait, answer = #{answer}"
answer

# Server side
Meteor.methods average_mileage: ->
console.log "server mileage called"
total = count = 0
r = Mileage.find({}).forEach (mileage) ->
total += mileage.mileage
count += 1
console.log "server about to return #{total / count}"
total / count

这似乎可以正常工作,但事实并非如此,因为据我所知 Meteor.call 是一个异步调用,而 answer 将始终为 null返回。在服务器上处理东西似乎是一个很常见的用例,我一定只是忽略了一些东西。那会是什么?

谢谢!

最佳答案

从 Meteor 0.6.5 开始,集合 API 还不支持聚合查询,因为没有(直接的)方法可以对它们进行实时更新。但是,您仍然可以自己编写它们,并在 Meteor.publish 中提供它们,尽管结果是静态的。在我看来,这样做仍然更可取,因为您可以合并多个聚合并使用客户端集合 API。

Meteor.publish("someAggregation", function (args) {
var sub = this;
// This works for Meteor 0.6.5
var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;

// Your arguments to Mongo's aggregation. Make these however you want.
var pipeline = [
{ $match: doSomethingWith(args) },
{ $group: {
_id: whatWeAreGroupingWith(args),
count: { $sum: 1 }
}}
];

db.collection("server_collection_name").aggregate(
pipeline,
// Need to wrap the callback so it gets called in a Fiber.
Meteor.bindEnvironment(
function(err, result) {
// Add each of the results to the subscription.
_.each(result, function(e) {
// Generate a random disposable id for aggregated documents
sub.added("client_collection_name", Random.id(), {
key: e._id.somethingOfInterest,
count: e.count
});
});
sub.ready();
},
function(error) {
Meteor._debug( "Error doing aggregation: " + error);
}
)
);
});

以上是一个示例分组/计数聚合。一些注意事项:

  • 执行此操作时,您自然会在 server_collection_name 上进行聚合,并将结果推送到名为 client_collection_name 的不同集合中。
  • 此订阅不会生效,并且可能会在参数更改时更新,因此我们使用了一个非常简单的循环,将所有结果推送出去。
  • 聚合的结果没有 Mongo ObjectID,所以我们自己生成一些任意的。
  • 聚合的回调需要封装在一个 Fiber 中。我在这里使用 Meteor.bindEnvironment 但也可以使用 Future 进行更底层的控制。

如果您开始合并此类出版物的结果,则需要仔细考虑随机生成的 id 如何影响合并框。然而,一个简单的实现只是一个标准的数据库查询,除了在客户端使用 Meteor API 更方便。

TL;DR 版本:几乎在您从服务器推送数据的任何时候,publish 都比 method 更可取。

如需更多关于不同聚合方式的信息, check out this post

关于mongodb - Meteor 中的平均聚合查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18520567/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com