query on count of embedded documents

635 views
Skip to first unread message

robj

unread,
Oct 15, 2011, 10:39:14 PM10/15/11
to Mongoid
one post has_many attachments

I am trying to do a query for only posts with attachments

ie, something along the lines of:

posts.where(:attachments.length.gte => 1 ).count

this of course does not work, but is there anyway to achieve this with
a criteria query without reverting to something like:

@imageable.posts.each do |post|
if post.attachments.length > 0
@posts << post
end
end



Thanks


Durran Jordan

unread,
Oct 16, 2011, 2:18:07 AM10/16/11
to mon...@googlegroups.com
Unfortunately MongoDB does not provide a length comparison of arrays in it's query language, but you could achieve it with javascript. (Note that it would result in a full scan of the collection on the db side):

Post.where("this.attachments.length > 0")

2011/10/16 robj <robert....@gmail.com>

Nickolay Kolev

unread,
Oct 17, 2011, 7:05:27 AM10/17/11
to mon...@googlegroups.com
How about creating a counter cache field (named, say, attachments_count) and update in a before_save block?

rubish gupta

unread,
Oct 17, 2011, 11:54:19 PM10/17/11
to mon...@googlegroups.com

robj

unread,
Oct 18, 2011, 8:17:48 PM10/18/11
to Mongoid
Hi Rubish, that solution would work if the attachments were
referenced, but in this case they are embedded.

I will go with the counter cache field as described by Nickolay, as id
like to keep this a criteria query so I can still simply use
pagination.

Thanks all


On Oct 17, 8:54 pm, rubish gupta <rubish.gu...@almaconnect.com> wrote:
> http://stackoverflow.com/questions/6515800/can-rails-scopes-filter-on...

Jeffrey Jones

unread,
Oct 18, 2011, 8:28:38 PM10/18/11
to mon...@googlegroups.com
Seems really crappy that you cannot easily check the size for embedded
documents since they...well, they are embedded!

Maybe submit a feature request to 10gen?

Durran Jordan

unread,
Oct 19, 2011, 4:40:00 AM10/19/11
to mon...@googlegroups.com
There already is an open issue for this:

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

2011/10/19 Jeffrey Jones <jjo...@toppan-f.co.jp>
Reply all
Reply to author
Forward
0 new messages