mongodb native driver get collection names without database name
Asked Answered
N

2

9

How can I get collection names without database name from mongodb native driver for nodeJS?

db.collectionNames(function(err, collections) {
      if (err) {
        log.error(err);
      } else {
        log.info(collections);
      }
    });

This code returns something like this:

databaseName.collection1, databaseName.collection2, databaseName.collection3

But i want to get names: collection1, collection2, collection3

Nordau answered 17/5, 2014 at 6:45 Comment(0)
S
2

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.

Smaragd answered 17/5, 2014 at 7:12 Comment(0)
F
14

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"}]
});
Fetid answered 4/6, 2015 at 15:9 Comment(0)
S
2

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.

Smaragd answered 17/5, 2014 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.