Tony1221
Tony1221

Reputation: 21

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.

Upvotes: 1

Views: 3463

Answers (3)

Wan B.
Wan B.

Reputation: 18835

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.

Upvotes: 5

Grzegorz Żur
Grzegorz Żur

Reputation: 49181

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())

Upvotes: 4

vicky
vicky

Reputation: 415

in mongodb

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

Upvotes: 0

Related Questions