My user has this field :
interestedIn: [{
type: String,
enum: [
'art',
'sport',
'news',
'calture',
...
],
}],
and my video has this field:
categories: [{
type: String,
enum: [
'art',
'sport',
'news',
'calture',
...
],
}],
So I need a Video query that has the following conditions:
- Query to all videos and sort by values in req.user.interestedIn first.
- Rest of the videos that are not match to req.user.interestedIn get in the last.
I got this far with said query:
Video.aggregate([
{ '$match': {}},
{ '$unwind': '$categories' },
{ '$match': {categories: {$in: req.user.interestedIn}}},
{ '$group': {
'_id': '$categories',
'categories': { '$push': '$categories' }
}},
{ '$sort': { 'categories': 1 } }
])
This is the result:
"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}} ])