Following is the code for fetching the results from the db providing collection, filter query, sorting query and number of limit.
func DBFetch(collection *mongo.Collection, filter interface{}, sort interface{}, limit int64) ([]bson.M, error) {
findOptions := options.Find()
findOptions.SetLimit(limit)
findOptions.SetSort(sort)
cursor, err := collection.Find(context.Background(), filter, findOptions)
var result []bson.M
if err != nil {
logger.Client().Error(err.Error())
sentry.CaptureException(err)
cursor.Close(context.Background())
return nil, err
}
if err = cursor.All(context.Background(), &result); err != nil {
logger.Client().Error(err.Error())
sentry.CaptureMessage(err.Error())
return nil, err
}
return result, nil
}
- I am using mongo-go driver version 1.8.2
- mongodb community version 4.4.7 sharded mongo with 2 shards
- Each shard is with 30 CPU in k8 with 245Gb memory having 1 replica
- 200 rpm for the api
- Api fetches the data from mongo and format it and the serves it
- We are reading and writing both on primary.
- Heavy writes occur every hour approximately.
- Getting timeouts in milliseconds ( 10ms-20ms approx. )