mongodb native driver get collection names without database name
With the MongoDB 2.0.0 driver and higher, you'll need to use listCollections()
, as in
db.listCollections().toArray(function(err, collections){ //collections = [{"name": "coll1"}, {"name": "coll2"}]});
The exact structure of the response is a sub-document with the "name" key in an array:
[ { name: 'test.cursors' }, { name: 'test.episodes' }, { name: 'test.zips' }, { name: 'test.scripts' }]
So just use map
with a regex replace
:
db.collectionNames(function(err, collections) { console.log( collections.map(function(x) { return x.name.replace(/^([^.]*)./,""); }) );});
And that will strip out everything up to the first .
which is the database prefix. Just in case you actually have collection names with a .
in them.