MongoDB:调用Count()与跟踪集合中的计数 [英] MongoDB: Calling Count() vs tracking counts in a collection
问题描述
我正在将消息传递系统迁移到MongoDB,并且很好奇如何处理各种统计信息,例如每个用户的消息数等.在MS SQL数据库中,我有一个表,其中每个用户的计数不同,它们得到了通过在相应表上的触发器进行更新,因此,例如,我可以知道UserA拥有多少未读消息,而无需调用昂贵的SELECT Count(*)
操作.
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.
MongoDB中的count
函数是否也很昂贵?
我开始阅读有关map/reduce的信息,但是我的网站负载很大,因此统计信息必须实时更新,我的理解是map/reduce的操作非常耗时.
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.
在MongoDB中收集各种汇总计数的最佳(性能方面)方法是什么?
What would be the best (performance-wise) approach on gathering various aggregate counts in MongoDB?
推荐答案
如果您有很多数据,那么我会坚持使用相同的方法,并在为用户添加新消息时增加聚合计数器. ,使用类似这样的集合:
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:
计数
{
userid: 123,
messages: 10
}
不幸的是(或幸运的是?)MongoDB中没有触发器,因此您需要从应用程序逻辑中增加计数器:
Unfortunately (or fortunately?) there are no triggers in MongoDB, so you'd increment the counter from your application logic:
db.counts.update( { userid: 123 }, { $inc: { messages: 1 } } )
这将为您提供最佳性能,并且您可能还会在userid
字段上添加索引以进行快速查找:
This'll give you the best performance, and you'd probably also put an index on the userid
field for fast lookups:
db.counts.ensureIndex( { userid: 1 } )
这篇关于MongoDB:调用Count()与跟踪集合中的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!