From the scale of the dataset, I am guessing it is likely to be some datalake collection that might have a high read-write ratio. i.e. read frequently but not updated frequently. If that is the case and your parameter does not change frequently, you may consider precomputing the priority and store each execution's results in a separate collection such that you can refer the same execution result in future.
db.collection.aggregate([
{
"$set": {
priority: {
$let: {
vars: {
prefixChar: "A",
latterword: "XYZ"
},
"in": {
"$switch": {
"branches": [
{
"case": {
"$and": [
{
"$eq": [
"$prefix",
"$$prefixChar"
]
},
{
"$ne": [
{
"$ifNull": [
"$number",
null
]
},
null
]
},
{
"$eq": [
"$latter",
"$$latterword"
]
}
]
},
"then": 1
},
{
"case": {
"$and": [
{
"$ne": [
{
"$ifNull": [
"$prefix",
null
]
},
null
]
},
{
"$ne": [
{
"$ifNull": [
"$number",
null
]
},
null
]
},
{
"$eq": [
"$latter",
"$$latterword"
]
}
]
},
"then": 2
},
{
"case": {
"$and": [
{
"$eq": [
"$prefix",
"$$prefixChar"
]
},
{
"$ne": [
{
"$ifNull": [
"$number",
null
]
},
null
]
},
{
$eq: [
0,
{
"$indexOfCP": [
"$latter",
{
"$substrCP": [
"$$latterword",
0,
2
]
}
]
}
]
}
]
},
"then": 3
},
{
"case": {
"$and": [
{
"$eq": [
"$prefix",
"$$prefixChar"
]
},
{
"$ne": [
{
"$ifNull": [
"$number",
null
]
},
null
]
},
{
$eq: [
0,
{
"$indexOfCP": [
"$latter",
{
"$substrCP": [
"$$latterword",
0,
1
]
}
]
}
]
}
]
},
"then": 4
},
{
"case": {
"$and": [
{
"$eq": [
"$prefix",
"$$prefixChar"
]
},
{
"$ne": [
{
"$ifNull": [
"$number",
null
]
},
null
]
},
{
"$ne": [
{
"$ifNull": [
"$latter",
null
]
},
null
]
}
]
},
"then": 5
}
],
"default": 6
}
}
}
}
}
},
{
"$group": {
"_id": "$priority",
"docIds": {
"$push": "$_id"
}
}
},
{
"$set": {
"_id": {
"executionId": "fill in your preferred id",
"priority": "$_id",
"prefixChar": "A",
"latterword": "XYZ"
}
}
},
{
"$merge": {
"into": "precomputed"
}
}
])
Mongo Playground
Afterwards, when you are trying to fetch the result, you can start a $lookup
from your precomputed
collection. The precomputed collection can be indexed to boost the performance.
db.precomputed.aggregate([
{
"$match": {
"_id.executionId": "fill in your preferred id"
}
},
{
"$sort": {
"_id.priority": 1
}
},
{
"$unwind": "$docIds"
},
{
"$limit": 12
},
{
"$lookup": {
"from": "collection",
"localField": "docIds",
"foreignField": "_id",
"as": "rawDocsLookup"
}
},
{
"$unwind": "$rawDocsLookup"
},
{
"$replaceRoot": {
"newRoot": {
"$mergeObjects": [
"$rawDocsLookup",
{
priority: "$_id.priority"
}
]
}
}
}
])
Mongo Playground
{$exists: true}
and{$ne:null}
See the different results from Ployground-ne-null and Playground-exists. These may also interact differently with indexing, and have performance implications at scale. – Sylvester