虚拟属性的Mongoid查询数据库 [英] Mongoid Query DB by Virtual Attribute
问题描述
背景:我有两个帖子和用户,它们都是HABTM社区.在我的帖子模型中,我有一种方法,可以通过比较他们共同拥有多少个社区来计算与给定用户的帖子相关性:
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)
或
查询所有帖子并按相关性对它们进行排序,即
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.
推荐答案
You can do this in mongoDB using Aggregation Framework (new in version 2.2).
您必须具有一系列可用的用户社区.在此示例中,我将其称为userComms-我期望它是一个具有与posts.communities相同类型的值的数组.
You have to have the array of User's communities available. I'll call it userComms in this example - I'm expecting it to be an array with the same type of values that posts.communities are.
db.posts.aggregate( [
{
"$unwind" : "$communities"
},
{
"$match" : {
"communities" : {
"$in" : userComms
}
}
},
{
"$group" : {
"_id" : "$_id",
"relevance" : {
"$sum" : 1
}
}
},
{
"$sort" : {
"relevance" : -1
}
}
]);
这将返回以下格式的文档:
This returns a document of the form:
{
"result" : [
{
"_id" : 1,
"relevance" : 4
},
{
"_id" : 6,
"relevance" : 3
},
...
]
}
结果数组包含帖子的_id,并且与帖子相关,通过添加与用户共有的社区数来计算.然后按该总和排序(降序).
The result array contains _ids of posts and relevant as computed by adding the number of communities they had in common with user. Then it's sorted (descending) by that sum.
这篇关于虚拟属性的Mongoid查询数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!