1

BACKGROUND: I have Posts and Users, both of which HABTM Communities. In my Post model, I have a method for calculating a post's relevance to a given user by comparing how many communities they have in common as such:

def relevance(user)
  (self.communities & user.communities).length
end

OBJECTIVE: To query Posts either by a given relevance i.e.

Post.where(:relevance => 3)

or

to query all posts and sort them by relevance i.e.

Post.all.desc(:relevance)

I know that the user variable is needed there somewhere, just wondering if something like this is possible or if a workaround exists.

4

1 回答 1

0

您可以使用聚合框架(2.2 版中的新功能)在 mongoDB 中执行此操作。

您必须拥有一系列可用的用户社区。在本例中,我将其称为 userComms - 我希望它是一个具有与 posts.communities 相同类型的值的数组。

db.posts.aggregate( [
    {
        "$unwind" : "$communities"
    },
    {
        "$match" : {
            "communities" : {
                "$in" : userComms
            }
        }
    },
    {
        "$group" : {
            "_id" : "$_id",
            "relevance" : {
                "$sum" : 1
            }
        }
    },
    {
        "$sort" : {
            "relevance" : -1
        }
    }
]);

这将返回以下形式的文档:

{
    "result" : [
        {
            "_id" : 1,
            "relevance" : 4
        },
        {
            "_id" : 6,
            "relevance" : 3
        },
...
        ]
}

结果数组包含帖子的 _ids 和相关性,通过添加他们与用户共同拥有的社区数量来计算。然后按该总和对其进行排序(降序)。

于 2012-08-28T23:00:05.637 回答