Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb native driver get collection names without database name

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

like image 702
Michael Skvortsov Avatar asked May 17 '14 06:05

Michael Skvortsov


People also ask

How do I find collection name in MongoDB?

To list all collections in Mongo shell, you can use the function getCollectionNames().

What is native MongoDB driver?

The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.

Does MongoDB Create collection if not exists?

If a collection does not exist, MongoDB creates the collection when you first store data for that collection. You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.

How do I read a collection in MongoDB?

Fetch all data from the collection If we want to fetch all documents from the collection the following mongodb command can be used : >db. userdetails. find(); or >db.


2 Answers

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"}]
});
like image 107
dshapiro Avatar answered Nov 13 '22 16:11

dshapiro


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.

like image 35
Neil Lunn Avatar answered Nov 13 '22 15:11

Neil Lunn