简体   繁体   中英

Enable random access to collection with MongoDB

I have a Rails application. It has a feed that shows items from different users all mixed up. It would be something similar to Pinterest in the way you see these items.

Right now I show all these items ordered by its date of creation. However, as the items are created by batches by users, they are shown not randomly (say you se the first 6 items being from one user, then the other 5 from other one, etc.).

The code that serves the items is this:

class Feeder

    def self.most_recent_created(watching_user=nil, current_cursor)

        next_cursor = nil
        feed = []
        influencers_ids = User.influencers.distinct(:_id)

        Rating.most_recent_from_influencers(watching_user, influencers_ids).scroll(current_cursor) do |rating, cursor|
            next_cursor = cursor
            feed << ImoPresenter.new(Imo.new(rating), watching_user)
        end

        feed << next_cursor.to_s

    end

end

scroll just gives a cursor pointing to each item in the iteration. Then I push the item into the feed.

The access to the database is done in Rating.most_recent_from_influencers(watching_user, influencers_ids), where most_recent_from_influencers(watching_user, influencers_ids) is a scope defined as follows:

scope :not_from, ->(user) { ne(user_id: user.id) }
scope :from, ->(user_ids) { any_in(user_id: user_ids) }
scope :most_recent_from_influencers, ->(watching_user, influencers_ids) {
        proxy = from(influencers_ids).over_zero.desc(:created_at).limit(IMOS_PER_PAGE)
        proxy = proxy.not_from(watching_user) if watching_user
        proxy
    }

MongoDB does not have random access out of the box. They suggest this for having a way of accessing randomly to the items. Basically, the solution is to add a random field in all documents and order the collection through this field. However, although I would have random items, I would always have almost the same items being shown, as I would just have the options of ordering it by desc(:rand) or asc(:rand) .

I would like to have suggestions on how I can make the items being shown truly in a random way. Is it possible?

Based on similar questions, I've come to the conclusion that having a random field is a valid solution if the collection is dynamic, meaning that documents are inserted frequently. The more dynamic the collection is, the more 'random' access you can have.

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