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
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.
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.
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.
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.
You can use db.getCollectionNames()
with Array.filter()
:
db.getCollectionNames().filter(function (collection) { return /pattern/.test(collection) })
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