我使用MongoDB集合上的聚合来聚合,分组和统计视频项目,以创建最受欢迎的视频列表。我想将相关数据存储到作者,日期,标题等视频中。我编写的函数有效,但每次视频在集合中时,它都会创建一个相同视频数据的数组。如何为项目仅将相关数据插入视频一次?
videos = Recentvideos.aggregate([
// Match the documents to every video downloaded in last 24 hours
{ "$match": {
"date": { "$gte": time }
}},
{ "$group": {
"_id": "$encodedUrl",
"count": { "$sum": 1 },
"docs": { "$push": {
"author": "$author",
"date": "$date",
"extractor": "$extractor",
"thumbnail": "$thumbnail",
"title": "$title",
}}
}},
// Sort from most downloaded to least
{ "$sort" : {
"count" : -1
}}
])
最近的视频收藏方式如下:
Recentvideos.insert({
extractor:extractor,
title:title,
author:author,
encodedUrl:encodedUrl,
thumbnail:thumbnail,
date:date,
});
答案 0 :(得分:1)
你能用$ first而不是$ push吗?
videos = Recentvideos.aggregate([
{ "$match": {
"date": { "$gte": time }
}},
{ "$group": {
"_id": "$encodedUrl",
"count": { "$sum": 1 },
"author": {$first: "$author"},
"date": {$first: "$date"},
"extractor": {$first: "$extractor"},
"thumbnail": {$first: "$thumbnail"},
"title": {$first: "$title"}
}},
{ "$sort" : {
"count" : -1
}}
])
看起来很简单,但所有这些accumulator operators都意味着返回一个结果(如$ sum)。 $ push创建一个数组。当然,这个解决方案将以不同的格式返回数据,但看起来你可能没问题。