@@ -10,6 +10,7 @@ import (
10
10
"peerprep/common"
11
11
12
12
"go.mongodb.org/mongo-driver/bson"
13
+ "go.mongodb.org/mongo-driver/mongo"
13
14
"go.mongodb.org/mongo-driver/mongo/options"
14
15
)
15
16
@@ -34,6 +35,36 @@ func (db *QuestionDB) GetAllQuestionsWithQuery(
34
35
return questions , nil
35
36
}
36
37
38
+ func (db * QuestionDB ) GetOneQuestionWithQuery (
39
+ logger * common.Logger ,
40
+ filter bson.D ,
41
+ ) (* common.Question , error ) {
42
+ // Define the aggregation pipeline with the $match and $sample stages
43
+ pipeline := mongo.Pipeline {
44
+ {{Key : "$match" , Value : filter }},
45
+ {{Key : "$sample" , Value : bson.D {{Key : "size" , Value : 1 }}}},
46
+ }
47
+
48
+ // Execute the aggregation pipeline
49
+ cursor , err := db .questions .Aggregate (context .Background (), pipeline )
50
+ if err != nil {
51
+ logger .Log .Error ("Error retrieving questions: " , err .Error ())
52
+ return nil , err
53
+ }
54
+
55
+ var questions []common.Question
56
+ if err = cursor .All (context .Background (), & questions ); err != nil {
57
+ logger .Log .Error ("Error decoding questions: " , err .Error ())
58
+ return nil , err
59
+ }
60
+
61
+ if len (questions ) == 0 {
62
+ return nil , nil
63
+ }
64
+
65
+ return & questions [0 ], nil
66
+ }
67
+
37
68
func (db * QuestionDB ) AddQuestion (logger * common.Logger , question * common.Question ) (int , error ) {
38
69
if db .QuestionExists (question ) {
39
70
logger .Log .Warn ("Cannot add question: question already exists" )
0 commit comments