MongoDB:调用 Count() 与跟踪集合中的计数
我正在将我们的消息系统转移到 MongoDB,并且很好奇对于各种统计数据(例如每个用户的消息数量等)采取什么方法。在 MS SQL 数据库中,我有一个表,其中每个用户有不同的计数,并且它们通过触发器进行更新例如,我可以知道 UserA 有多少条未读消息,而无需调用昂贵的 SELECT Count(*) 操作。
MongoDB 中的 count 函数也很昂贵吗? 我开始阅读有关 Map/Reduce 的内容,但我的网站负载很高,因此统计数据必须实时更新,我的理解是 Map/Reduce 是耗时的操作。
在 MongoDB 中收集各种聚合计数的最佳(性能方面)方法是什么?
I am moving our messaging system to MongoDB and am curious what approach to take with respect to various stats, like number of messages per user etc. In MS SQL database I have a table where I have different counts per user and they get updated by trigger on corresponding tables, so I can for example know how many unread messages UserA has without calling an expensive SELECT Count(*)
operation.
Is count
function in MongoDB also expensive?
I started reading about map/reduce but my site is high load, so statistics has to update in real time, and my understanding is that map/reduce is time consuming operation.
What would be the best (performance-wise) approach on gathering various aggregate counts in MongoDB?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Mongodb 非常适合数据非规范化。如果您的网站负载很高,那么您需要预先计算几乎所有内容,因此毫无疑问,请使用
$inc
来增加消息计数。Mongodb good fit for the data denormaliztion. And if your site is high load then you need to precalculate almost everything, so use
$inc
for incrementing messages count, no doubt.如果您有大量数据,那么我会坚持使用相同的方法,并在为用户添加新消息时增加聚合计数器,使用如下所示的集合:
counts
不幸的是(或者幸运的是?)MongoDB 中没有触发器,因此您可以从应用程序逻辑中增加计数器:
这将为您提供最佳性能,并且您可能还会在
userid 字段:
If you've got a lot of data, then I'd stick with the same approach and increment an aggregate counter whenever a new message is added for a user, using a collection something like this:
counts
Unfortunately (or fortunately?) there are no triggers in MongoDB, so you'd increment the counter from your application logic:
This'll give you the best performance, and you'd probably also put an index on the
userid
field for fast lookups: