Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB shell: how to search for collections which match a name or regex

when I use show collections it returns a list of all collections which is pretty long, how can I write a query to return collections matching a pattern. I was hoping for something like db.collections({name:/pattern/}) but couldn't find

like image 754
mike Avatar asked Oct 31 '14 22:10

mike


People also ask

How do I use regex to search MongoDB?

MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language. Unlike text search, we do not need to do any configuration or command to use regular expressions.

How do I find a particular collection in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.

Does MongoDB support regex?

MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support. For restrictions on particular syntax use, see $regex vs. /pattern/ Syntax.

How do I select a collection in MongoDB shell?

To obtain a list of MongoDB collections, we need to use the Mongo shell command show collections . This command will return all collections created within a MongoDB database. To be able to use the command, we'll first need to select a database where at least one collection is stored.


1 Answers

You can use db.getCollectionNames() with Array.filter():

db.getCollectionNames().filter(function (collection) { return /pattern/.test(collection) })
like image 139
Gergo Erdosi Avatar answered Nov 15 '22 08:11

Gergo Erdosi