1

I am playing around in the mongodb-shell trying to learn about mongodb, and noticed that db.stats() shows number of collections to be 1 more than what is shown by db.getCollectionNames()

Here is the example:

> db.stats();
{   
  "db" : "learn",
  "collections" : 6,
  "objects" : 47, 
  ...
  ...

  "ok" : 1 
}   

> db.getCollectionNames();
[ "hit_stats", "hits", "system.indexes", "system.profile", "unicorns" ]

So db.stats says there are 6 collections where as db.getCollectionNames lists only 5 collection names. Why this discrepancy?

Prakash Murthy
  • 12,923
  • 3
  • 46
  • 74

1 Answers1

2

You see this discrepancy because the system.namespaces collection which stores collection-information does not include itself. Example with 2 collections (items and user):

> db.system.namespaces.find()
{ "name" : "test.system.indexes" }
{ "name" : "test.items.$_id_" }      // index
{ "name" : "test.items" }
{ "name" : "test.users.$_id_" }      // index
{ "name" : "test.users" }

> db.stats()['collections']
4

> db.getCollectionNames()
[ "items", "system.indexes", "users" ]

As you can see system.namespaces does not include itself. db.stats() does include it in its calculation hence the 1 collection difference. Hope this makes sense.

Also see these bug reports SERVER-1162 and SERVER-1308.

Justin Case
  • 1,503
  • 11
  • 20