Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get all collections where collection name like '%2015%'?
To get all collections where the collection name contains a specific pattern like '%2015%', you can use MongoDB's getCollectionNames() method combined with JavaScript's filter() function and regular expressions.
Creating Sample Collections
Let us first create some collections that contain year numbers like 2015, 2019, etc ?
> use web;
switched to db web
> db.createCollection("2015-myCollection");
{ "ok" : 1 }
> db.createCollection("2019-employeeCollection");
{ "ok" : 1 }
> db.createCollection("2015-yourCollection");
{ "ok" : 1 }
Now you can display all the collections with the help of SHOW command ?
> show collections;
This will produce the following output ?
2015-myCollection 2015-yourCollection 2019-employeeCollection applyConditionDemo check creatingAliasDemo emp_info emptyCollection removeNullDemo
Filtering Collections by Pattern
Following is the query to get all collections where collection name contains '2015' ?
> db.getCollectionNames().filter(function (v) { return /^2015\-/.test(v); })
This will produce the following output ?
[ "2015-myCollection", "2015-yourCollection" ]
Finding Collections Starting with Different Years
If you want to check collection names beginning with 2019, implement the below query ?
> db.getCollectionNames().filter(function (v) { return /^2019\-/.test(v); })
This will produce the following output ?
[ "2019-employeeCollection" ]
The getCollectionNames() method returns an array of all collection names, and the filter() function with regular expressions allows you to match specific patterns in collection names efficiently.
