How to get all collections where collection name like '%2015%'?


Let us first create some collections that starts from year number i.e. 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 −

> show collections;

This will produce the following output −

2015-myCollection
2015-yourCollection
2019-employeeCollection
applyConditionDemo
check
creatingAliasDemo
emp_info
emptyCollection
removeNullDemo

Following is the query to get all collections where collection name like ‘%2015%’ −

> db.getCollectionNames().filter(function (v) { return /^2015\-/.test(v); })

This will produce the following output −

[ "2015-myCollection", "2015-yourCollection" ]

If you want to check collection name beginning with 2019, implement the below query −

> db.getCollectionNames().filter(function (v) { return /^2019\-/.test(v); })

This will produce the following output −

[ "2019-employeeCollection" ]

Updated on: 30-Jul-2019

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements