Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why a collection exists but can not find in show collections?

Tags:

mongodb

In the mongo shell, I can find records from collection stat by using such commands:

use gm;
gm.stat.find({});

but stat is not listed in show collection results.

like image 820
tuesday Avatar asked Aug 07 '13 09:08

tuesday


1 Answers

Any collection virtually exists all the time (i.e. you will not get an error saying that "you did not create a collection"). As soon as you insert the first document into a collection this will exist also physically (will be created on the disk). So if you really want to make sure a collection exists use:

db.getCollectionNames()

This will show you only the collections that had at least one document inserted into them, even if they are currently empty.

Once physically created, a collection can be deleted using the drop command:

db.myColl.drop()

This will delete it physically but the "virtual" one will still be there.

As for your example, running:

db.stat.insert({}); print("Collection stat exists:" + (db.getCollectionNames().indexOf("stat") !== -1));

will tell you:

Collection stat exists: true
like image 180
4 revs, 2 users 76% Avatar answered Oct 05 '22 21:10

4 revs, 2 users 76%