Last active
August 30, 2016 09:42
-
-
Save rgarcia/9263299 to your computer and use it in GitHub Desktop.
mongo db stats
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"labix.org/v2/mgo" | |
"labix.org/v2/mgo/bson" | |
"log" | |
"os" | |
"strings" | |
"text/tabwriter" | |
) | |
type DBStats struct { | |
Collections int `bson:"collections"` | |
Objects int `bson:"objects"` | |
AvgObjSize float64 `bson:"avgObjSize"` | |
DataSize float64 `bson:"dataSize"` | |
StorageSize float64 `bson:"storageSize"` | |
FileSize float64 `bson:"fileSize"` | |
IndexSize float64 `bson:"indexSize"` | |
} | |
const ( | |
BytesPerGigabyte = 1073741824.0 | |
) | |
func main() { | |
// Format output in space-separated columns of minimal width 5 and at least | |
// one blank of padding (so wider column entries do not touch each other) | |
w := new(tabwriter.Writer) | |
w.Init(os.Stdout, 5, 0, 1, ' ', 0) | |
// Set up connection | |
session, err := mgo.Dial(os.Getenv("MONGO_URL")) | |
if err != nil { | |
log.Fatal(err) | |
} | |
db := session.DB(os.Getenv("MONGO_DB")) | |
// Get total database size | |
var dbStats DBStats | |
if err := db.Run(bson.D{{"dbStats", 1}, {"scale", 1}}, &dbStats); err != nil { | |
log.Fatal(err) | |
} | |
// Break it down by collection | |
collNames, _ := db.CollectionNames() | |
for _, collName := range collNames { | |
var collStats map[string]interface{} | |
if err := db.Run(bson.D{ | |
{"collStats", collName}, | |
{"scale", 1}, | |
}, &collStats); err != nil { | |
log.Fatal(err) | |
} | |
var gb float64 | |
switch collStats["size"].(type) { // (facepalm) sometimes this is int, sometimes float | |
case int: | |
gb = float64(collStats["size"].(int)) / BytesPerGigabyte | |
case float64: | |
gb = collStats["size"].(float64) / BytesPerGigabyte | |
} | |
fmt.Fprintln(w, strings.Join([]string{ | |
collName, | |
fmt.Sprintf("%0.2f GB", gb), | |
fmt.Sprintf("%0.2f%%", 100.0*gb/(dbStats.DataSize/BytesPerGigabyte)), | |
}, "\t")) | |
} | |
fmt.Fprintln(w, strings.Join([]string{ | |
"total data size", | |
fmt.Sprintf("%0.2f GB", dbStats.DataSize/BytesPerGigabyte), | |
"", | |
}, "\t")) | |
w.Flush() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment