I’m attempting to aggregate some stats in our mongo database using the go driver. Ultimately, I’m trying to find out:
- the number of databases with a prefix of BLURG
- the number of collections in the databases prefixed with BLURG
- the number of indices in the collections in the DBs prefixed with BLURG
- the size of the indices in the collections in the DBs prefixed with BLURG
(BLURG is a sample use-case with error handling removed - I’m interested in more prefixes in the real code)
dbs := map[string](interface{}){}
conn.GetDBWithoutIndexing("admin").RunCommand(context.Background(), bson.M{
"listDatabases": 1,
}).Decode(&dbs)
for _, database := range dbs["databases"].(primitive.A) {
d := database.(map[string]interface{})
dbName= d["name"].(string)
fmt.Println("Working on ", dbName)
// Find out the number of collections
cols, _ := conn.GetDBWithoutIndexing(dbName).ListCollectionNames(context.Background(), bson.M{})
for _, col := range cols {
cur, _ := conn.GetDBWithoutIndexing(dbName).C(col).Indexes().List(context.Background())
indices := []mongo.IndexModel{}
cur.All(context.Background(), &indices)
for _, index := range indices {
fmt.Printf("%#v\n", index.Keys)
}
}
switch {
case strings.HasPrefix(dbName, "BLURG_"):
devDBs++
default:
nonEnvDBs++
}
Now a couple issues with this code:
- Indexes refuse to unpack into IndexModel from Indexes().List(). No errors, but the Keys interface is nil
- I couldn’t figure out how to obtain the index size
- Biggest issue, I will be making tens of thousands of calls to our production DB cluster Admittedly, I can target a slave, but still, I’m hoping that maybe someone can offer a better optimization.