Skip to content

Commit

Permalink
optimizing mongodb aggregation
Browse files Browse the repository at this point in the history
  • Loading branch information
Marchand-Nicolas committed Jan 8, 2024
1 parent fac1e5d commit 3443691
Showing 1 changed file with 40 additions and 72 deletions.
112 changes: 40 additions & 72 deletions src/endpoints/quest_boost/get_completed_boosts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,103 +25,71 @@ pub async fn handler(
let address = query.addr.to_string();
let pipeline = vec![
// Existing pipeline to get completed quests
doc! {
"$match": doc! {
"address": address
}
},
doc! {
"$lookup": doc! {
"from": "tasks",
"localField": "task_id",
"foreignField": "id",
"as": "associatedTask"
}
},
doc! {
"$unwind": "$associatedTask"
},
doc! {
"$group": doc! {
"_id": "$associatedTask.quest_id",
"done": doc! {
"$sum": 1
}
}
},
doc! {
"$lookup": doc! {
"from": "tasks",
"localField": "_id",
"foreignField": "quest_id",
"localField": "quests",
"foreignField": "quest_id", // Replace 'questId' with the actual field name in your tasks collection
"as": "tasks"
}
},
doc! {
"$match": doc! {
"$expr": doc! {
"$eq": [
"$done",
doc! {
"$size": "$tasks"
}
]
}
}
},
doc! {
"$project": doc! {
"quest_id": "$_id",
"_id": 0
}
},
// New stages to match completed quests with boosts
doc! {
"$lookup": doc! {
"from": "boosts",
"let": { "completedQuest": "$quest_id" },
"pipeline": vec![
doc! {
"$match": doc! {
"$expr": doc! {
"$in": [ "$$completedQuest", "$quests" ]
"from": "completed_tasks",
"let": {
"task_ids": {
"$map": {
"input": "$tasks",
"as": "taskObj",
"in": "$$taskObj.id" // Extract the id from each object in the tasks array
}
}
},
"pipeline" : [
{
"$match": {
"$expr": {
"$and": [
{
"$in": ["$task_id", "$$task_ids"],
},
{
"$eq": ["$address", address],
}
]
}
}
},
}
],
"as": "matchedBoosts"
}
},
doc! {
"$unwind": "$matchedBoosts"
},
doc! {
"$group": doc! {
"_id": "$matchedBoosts.id",
"boostDetails": doc! { "$first": "$matchedBoosts" },
"matchedQuestsCount": doc! { "$sum": 1 }
"as": "completed_tasks"
}
},
doc! {
"$match": doc! {
"$expr": doc! {
"$eq": [ "$matchedQuestsCount", doc! { "$size": "$boostDetails.quests" } ]
}
"$expr": {
"$eq": [
{
"$size": "$tasks",
},
{
"$size": "$completed_tasks",
},
],
},
}
},
doc! {
"$project": doc! {
"boost_id": "$_id",
"_id": 0
"$project": {
"id": 1,
}
},
];
let collection = state.db.collection::<Document>("completed_tasks");
let collection = state.db.collection::<Document>("boosts");
match collection.aggregate(pipeline, None).await {
Ok(mut cursor) => {
let mut boosts: Vec<u32> = Vec::new();
while let Some(result) = cursor.try_next().await.unwrap() {
boosts.push(result.get("boost_id").unwrap().as_i64().unwrap() as u32);
boosts.push(result.get("id").unwrap().as_i64().unwrap() as u32);
}
(StatusCode::OK, Json(boosts)).into_response()
}
Expand Down

0 comments on commit 3443691

Please sign in to comment.