【发布时间】:2023-03-13 09:13:01
【问题描述】:
我的用户有这个字段:
interestedIn: [{
type: String,
enum: [
'art',
'sport',
'news',
'calture',
...
],
}],
我的视频有这个字段:
categories: [{
type: String,
enum: [
'art',
'sport',
'news',
'calture',
...
],
}],
所以我需要一个满足以下条件的视频查询:
- 首先查询所有视频并按req.user.interestedIn中的值排序。
- 其余与 req.user.interestedIn 不匹配的视频排在最后。
我通过上述查询得到了这么多:
Video.aggregate([
{ '$match': {}},
{ '$unwind': '$categories' },
{ '$match': {categories: {$in: req.user.interestedIn}}},
{ '$group': {
'_id': '$categories',
'categories': { '$push': '$categories' }
}},
{ '$sort': { 'categories': 1 } }
])
这是结果:
"videos": [
{
"_id": "art",
"categories": [
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art"
]
},
{
"_id": "news",
"categories": [
"news",
"news",
"news",
"news",
"news",
"news",
"news",
"news",
"videos": [
{
"_id": "art",
"categories": [
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art",
"art"
]
},
{
"_id": "news",
"categories": [
"news",
"news",
"news",
"news",
"news",
"news",
"news",
"news",
"news",
"news",
"news",
"news",
"news",
"news"
]
}
]
}
【问题讨论】:
-
类似
Video.aggregate([ { '$match': {}}, { '$unwind': '$categories' }, {"$addFields":{ "sortorder":{"$indexOfArray":[req.user.interestedIn, "$categories"]}}}, {"$sort":{"sortorder":-1}} ]) -
@Veeram tnx 回答。我得到查询结果,但我在 db 中有 100 个视频,结果显示 367。我认为查询聚合抛出数组中的每个元素(InterestedIn)。
-
你能给出预期的响应吗?您需要按类别对视频进行分组吗?
-
我只需要先按现有的 InterestedIn 对我的视频进行排序
-
还是不清楚。我们如何比较 category 和 InterestIn 数组?由于两者都是数组,比较应该是什么样子?
标签: node.js mongodb mongoose aggregation-framework