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
To list all collections in Mongo shell, you can use the function getCollectionNames().
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With