我正在开发一个简单的dev-meet-designer平台,我正在努力创建一个更好的流行度排名算法。
我现有的代码是:
project_collection.aggregate([
{ "$project": {
"score": {
"$divide": [
"$views",
{ "$divide": [
{ "$subtract": [
new Date(),
"$created_at"
]},
10*60*30
]}
]},
"created_at": 1,
"views": 1
}}
], function(error, results) {
// do stuff
});
我想切换代码来计算文档中的likers
数组,并使用该值代替$views
。非常感谢任何帮助!
这是一个示例文档结构:
{
"_id" : ObjectId("53d95d33a3ca780d096e5e7e"),
"name" : "Foo",
"tagline" : "This is a test project.",
"description" : "Foo bar.",
"tags" : [
"front end"
],
"owner" : "Noah",
"views" : 2,
"activity" : [
{
"options" : {
"type" : "started",
"owner" : "Noah"
}
},
{
"options" : {
"type" : "application",
"applicant" : "John"
}
}
],
"closed" : false,
"finished" : false,
"applicants" : [ "John" ],
"partners" : [],
"chat" : [],
"discussion" : [],
"url" : "",
"fireQuene" : [],
"likers" : [ "John", "Noah" ],
"created_at" : ISODate("2014-07-30T21:01:39.421Z")
}
答案 0 :(得分:0)
获得"数组长度"正如你的问题要求MongoDB 2.6引入了$size
运算符,它返回一个数组的长度。用来取代" $ views"在你的算法中,这将是:
project_collection.aggregate([
{ "$project": {
"score": {
"$divide": [
{ "$size": "$likers" },
{ "$divide": [
{ "$subtract": [
new Date(),
"$created_at"
]},
10*60*30
]}
]},
"created_at": 1,
"views": 1
}}
], function(error, results) {
// do stuff
});
如果您的早期版本没有此功能,则需要在阵列上使用$unwind
并$sum
进行计数。您可以进入$group
阶段:
project_collection.aggregate([
{ "$unwind": "$likers" },
{ "$group": {
"_id": "$_id",
"created_at": { "$first": "$created_at" },
"likers": { "$push": "$likers" },
"count": { "$sum": 1 }
}},
{ "$project": {
"score": {
"$divide": [
"$count",
{ "$divide": [
{ "$subtract": [
new Date(),
"$created_at"
]},
10*60*30
]}
]},
"created_at": 1,
"views": 1
}}
], function(error, results) {
// do stuff
});
所以$size
可以帮助你做你正在做的事情,但另外一般来说,尝试保持一个"计数"您的文档中的喜欢者并相应地更新。