Re: [mongodb-user] count operator when retrieving subset of fields

34 views
Skip to first unread message

Scott Hernandez

unread,
Jun 28, 2012, 9:07:12 AM6/28/12
to mongod...@googlegroups.com
There are requests for features like this, yes. Fundamentally the data stored on the server doesn't have the count either, without counting all the array elements. In order to make this faster it is best to keep the count up to date yourself by storing a count next to the array in a field like votersCount. Then every time you add something you can also increase the counter. The one tricky part is that you must check to see if your addToSet succeeded or not to know if your were correct to increase the counter.

https://jira.mongodb.org/browse/SERVER-1144

On Thu, Jun 28, 2012 at 7:42 AM, mgobeil <marc....@gmail.com> wrote:
Say I have a document like this and I want a voter count:

post { voters: [1, 2, 7, 6] }

I can't increment a separate counter like voterCount without reading the record before updating it to check for duplicates, so when writing I just want to use $addToSet.

But then, on the read side, if all I want is the count of post.voters there doesn't seem to be any way to get it without loading the (possibly very large) list of voters, only to do a .size() on the array and throw it out.


It seems to me like there should be something like slice, but for count:

db.posts.find({}, {voters:{$slice: 5}}) // first 5 voters
db.posts.find({}, {voters:{$count: 1}}) // return count of voters instead of voters array
 
Is a feature like that in the works, or is there another solution I'm missing? 

--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb

Reply all
Reply to author
Forward
0 new messages