简体   繁体   中英

Mongoid : Eager loading count on has_many association

I'm new with mongodb.

I'm trying to list some documents, my class has a has_many association, I would like to display the number of documents from this association.

Do I need to do some eager loading ?

If I use includes all the documents will be loaded, I only want the count.

Identity map is enabled

I don't know of a way to prevent eager loading from loading the full document. I'd be curious to hear if that's possible now.

You can get the count like this:

ChildDoc.where(myclass_id: myclass_obj.id).count

So you're querying on the implicitly created foreign key field of the association. This is still a query per parent doc, but the ideally fast query.

If perf is a real concern for you, you could write a single query that would return more data but in a single trip -- all the ids of the contained docs -- like this:

ChildDoc.where(myclass_id: {"$in" => list_of_myclass_objs.map {|x| x.id}}).only(:id, :myclass_id)

Since you're new to this, I'll add that you probably want to create the index on the FK field yourself -- mongoid doesn't do this for you.

class ChildDoc
    include Mongoid::Document
    belongs_to :myclass
    index({ myclass_id: 1 })
end

and then

rake db:mongoid:create_indexes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM