我使用过MongoDB聚合,当我尝试使用sort和limit时,我会得到重复的记录。
如下所示,我有3个文档,其中document1
和document2
具有相同的标题,document3
具有不同的视频标题。
我想按标题对文档进行分组,并按序列集按顺序对分组文档进行排序。
document1
和document2
将在同一个群组中,并且会获得唯一的文档2,然后我想要将此document2
和document3
与video_view_count
进行排序
/* document1 */
{
"_id" : ObjectId("580afd565706467c1bbabd70"),
"serial_episode" : "5",
"video_view_count" : 50.0,
"video_data" : [
{
"video_categories" : [
"Sport"
],
"video_title" : "Zwyci??zca",
"language_id" : "578f1ec6e494f9400b21fec4"
},
{
"video_featured_text" : "",
"video_categories" : [
"Sport"
],
"video_title" : "Zwyci??zca",
"language_id" : "578f1ec6e494f9400b21fec3"
}
]
}
/* document2 */
{
"_id" : ObjectId("580afd565706467c1bbabd71"),
"serial_episode" : "6",
"video_view_count" : 10.0,
"video_data" : [
{
"video_categories" : [
"Sport"
],
"video_title" : "Zwyci??zca",
"language_id" : "578f1ec6e494f9400b21fec4"
},
{
"video_featured_text" : "",
"video_categories" : [
"Sport"
],
"video_title" : "Zwyci??zca",
"language_id" : "578f1ec6e494f9400b21fec3"
}
]
}
/* document3 */
{
"_id" : ObjectId("580afd565706467c1bbabd72"),
"serial_episode" : "",
"video_view_count" : 11.0,
"video_data" : [
{
"video_categories" : [
"Sport"
],
"video_title" : "Zwyci??zca123",
"language_id" : "578f1ec6e494f9400b21fec4"
},
{
"video_featured_text" : "",
"video_categories" : [
"Sport"
],
"video_title" : "Zwyci??zca123",
"language_id" : "578f1ec6e494f9400b21fec3"
}
]
}
Expexcted Output:
我希望结果为document3
,然后是document2
,因为docuemnt1-2组合在一起以生成uniqe document2
,docuemnt2
包含最新一集。
我需要将document2
和document3
与视频观看次数进行比较:
/* document3 */
{
"_id": ObjectId("580afd565706467c1bbabd72"),
"serial_episode": "",
"video_view_count": 11,
"video_data": [
{
"video_categories": [
"Sport"
],
"video_title": "Zwyci??zca123",
"language_id": "578f1ec6e494f9400b21fec4"
},
{
"video_featured_text": "",
"video_categories": [
"Sport"
],
"video_title": "Zwyci??zca123",
"language_id": "578f1ec6e494f9400b21fec3"
}
]
},
/* document3 */
{
"_id": ObjectId("580afd565706467c1bbabd71"),
"serial_episode": "6",
"video_view_count": 10,
"video_data": [
{
"video_categories": [
"Sport"
],
"video_title": "Zwyci??zca",
"language_id": "578f1ec6e494f9400b21fec4"
},
{
"video_featured_text": "",
"video_categories": [
"Sport"
],
"video_title": "Zwyci??zca",
"language_id": "578f1ec6e494f9400b21fec3"
}
]
}
当前聚合操作:
// Grouping that I have implemented
var group = {
"$group": {
"_id":" $video_data.video_title",
"video_rating" : { $first:" $video_rating" },
"serial_episode" : { $first: "$serial_episode" },
"video_view_count": { $first: "$video_view_count" },
}
};
// Aggregate function to get that videos
videos.aggregate([
{ $match: { "video_data.video_categories": query.category_name } },
{ $unwind: "$video_data" },
{ $sort: { video_view_count: -1 } },
{ $sort:{ serial_episode: -1 } },
group,
{ $sort:{ video_view_count: -1 } },
{ $skip: skipData },
{ $limit: 10 }
], function(error, output){});
答案 0 :(得分:0)
你为什么要解开它? 移除展开,它会将文档与数组长度相乘..