Introduction to MongoDB collection.stats() Method

stats() is a method in MongoDB that can be used to retrieve statistics information about a collection.

Syntax

The syntax of the stats() method is as follows:

db.collection.stats(options)

Here, db.collection represents the collection from which to obtain information, and options is an optional parameter used to specify some options for obtaining statistical information, such as whether to include indexes.

Use Cases

The stats() method is usually used to obtain statistical information about a collection, including the size of the collection, the number of documents, the number of indexes, etc. This information can help you better understand the structure and performance of the collection, so that you can optimize and tune it.

Examples

Here is an example of using the stats() method to obtain statistical information about a collection.

Suppose we have a collection named products, which contains the following four documents:

{ "_id": 1, "name": "Product 1", "price": 10 }
{ "_id": 2, "name": "Product 2", "price": 20 }
{ "_id": 3, "name": "Product 3", "price": 30 }
{ "_id": 4, "name": "Product 4", "price": 40 }

We can use the following code to obtain statistical information about the products collection:

db.products.stats()

After executing the above code, the following statistical information will be returned:

{
   "ns": "test.products",
   "size": 184,
   "count": 4,
   "avgObjSize": 46,
   "storageSize": 16384,
   "numExtents": 0,
   "nindexes": 1,
   "lastExtentSize": 16384,
   "paddingFactor": 1,
   "systemFlags": 1,
   "userFlags": 0,
   "totalIndexSize": 16384,
   "indexSizes": {
      "_id_": 16384
   },
   "ok": 1
}

Here, ns represents the namespace of the collection, size represents the size of the collection, count represents the number of documents in the collection, avgObjSize represents the average size of each document, nindexes represents the number of indexes in the collection, indexSizes represents the size of each index, and so on.

Conclusions

The stats() method is a method in MongoDB that can be used to obtain statistical information about a collection. When using this method, you need to specify the collection from which to obtain information. In addition, you can specify some options for obtaining statistical information through the options parameter.