MongoDB: Calling Count() vs tracking counts in a collection

泪湿孤枕 提交于 2020-01-01 04:54:12

问题


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?


回答1:


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

{
    userid: 123,
    messages: 10
}

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 } } )

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 } )



回答2:


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.



来源:https://stackoverflow.com/questions/6054464/mongodb-calling-count-vs-tracking-counts-in-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!