简体   繁体   中英

How to get the size of a collection by mongo-go-driver

I need to get the size of the mongo database collection.
The project is written in golang using mongo-go-driver .

I need to get the size of the mongo database collection.

You can get a variety of storage statistics of MongoDB collection using collStats command. You can utilise Database.RunCommand to execute database commands with MongoDB Go driver . For example:

db := client.Database("databaseName")

result := db.RunCommand(context.Background(), bson.M{"collStats":"collectionname"})

var document bson.M
err = result.Decode(&document)

if err !=nil {
    panic(err)
}

fmt.Printf("Collection size: %v Bytes\n", document["size"])
fmt.Printf("Average object size: %v Bytes\n", document["avgObjSize"])
fmt.Printf("Storage size: %v Bytes\n", document["storageSize"])
fmt.Printf("Total index size: %v Bytes\n", document["totalIndexSize"])

The example above only print 4 information related to your question. However there are more information returned by collStats , you can see more information on Basic Stats Lookup example. You can also specify scale parameter to change the bytes to kilobytes, see Stats Lookup with Scale .

Note that the example above is written with mongo-go-driver v1.1.x.

There are two methods for checking this

The exact one with CountDocuments

count, err := client.Database("webshop").Collection("products").CountDocuments(context.Background(), bson.D{})

and estimation with EstimatedDocumentCount

count, err := client.Database("webshop").Collection("products").EstimatedDocumentCount(context.Background())

in mongodb

db.getCollection('collection').find({}).count()

In the mongo Shell, run the following command by replacing 'your_collection_name' with name of your collection:

db.your_collection_name.stats()

It returns statistics about the collection including size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM