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:
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"
]
}
]
}
In MongoDB, the $sort stage is used to sort all the documents in the aggregation pipeline and pass a sorted order to the next stage of the pipeline. Lets take a closer look at the above syntax: The $sort stage accepts a document that defines the field or fields that will be used for sorting.
To sort the whole array by value, or to sort by array elements that are not documents, identify the input array and specify 1 for an ascending sort or -1 for descending sort in the sortBy parameter.
This means $first returns the first order type for the documents between the beginning of the partition and the current document.
You can use $setIntersection
to extract the matching elements followed by $size
to count the matches.
$sort
descending documents on number of matches.
Something like
Video.aggregate([
{"$addFields":{ "numofmatches":{"$size":{"$setIntersection":["$categories", req.user.interestedIn]}}}},
{"$sort":{"numofmatches":-1}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With