recently i want to use mongodb driver to get all collections name by filter.
"Admin",
"Config",
"Event",
"event12345678901234567890123456789012",
"system.indexes"
above is the all collections name ,but i only want to show collection which start with 'event',and i found documents have a filter params,but the documents don't show any usage and filter rule,so is there anyone know how to use it?
Since getCollectionNames() is based on querying db.system.namespaces:
The <database>.system.namespaces collection contains information about all of the database’s collections. Additional namespace metadata exists in the database.ns files and is opaque to database users.
> db.getCollectionNames;
function (){
var all = [];
var nsLength = this._name.length + 1;
var c = this.getCollection( "system.namespaces" ).find();
while ( c.hasNext() ){
var name = c.next().name;
if ( name.indexOf( "$" ) >= 0 && name.indexOf( ".oplog.$" ) < 0 )
continue;
all.push( name.substring( nsLength ) );
}
return all.sort();
}
You can filter db.system.namespaces manually using $regex:
db.system.namespaces.find({'name': {"$regex": /^foo.Event\w*$/, "$options": "-i"}});
where foo is a database name, -i helps to make a case-insensitive search.
Demo (from "mongo shell"):
> db.system.namespaces.find();
{ "name" : "foo.system.indexes" }
{ "name" : "foo.system.users.$_id_" }
{ "name" : "foo.system.users.$user_1_userSource_1" }
{ "name" : "foo.system.users" }
{ "name" : "foo.foo.$_id_" }
{ "name" : "foo.foo" }
{ "name" : "foo.test.$_id_" }
{ "name" : "foo.test", "options" : { "create" : "test" } }
{ "name" : "foo.Config.$_id_" }
{ "name" : "foo.Config", "options" : { "create" : "Config" } }
{ "name" : "foo.Event.$_id_" }
{ "name" : "foo.Event", "options" : { "create" : "Event" } }
{ "name" : "foo.event12345678901234567890123456789012.$_id_" }
{ "name" : "foo.event12345678901234567890123456789012", "options" : { "create" : "event12345678901234567890123456789012" } }
{ "name" : "foo.Admin.$_id_" }
{ "name" : "foo.Admin", "options" : { "create" : "Admin" } }
> db.system.namespaces.find({'name': {"$regex": /^foo.Event\w*$/, "$options": "-i"}});
{ "name" : "foo.Event", "options" : { "create" : "Event" } }
{ "name" : "foo.event12345678901234567890123456789012", "options" : { "create" : "event12345678901234567890123456789012" } }