7

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

mike
  • 187
  • 3
  • 8
  • When you have so many collections in your database that you need to match them with regular expressions, you might want to reconsider your database architecture. In MongoDB, fewer collections are usually better. – Philipp Oct 31 '14 at 23:34

1 Answers1

18

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

db.getCollectionNames().filter(function (collection) { return /pattern/.test(collection) })
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
  • This is a perfect response and should be the accepted solution. – niczak Nov 15 '16 at 13:49
  • agreed helped me with the exact question +1 – FancyDolphin Feb 15 '17 at 03:36
  • What if I need to pass the pattern as a variable? For example; var patterns = ['pattern1', 'pattern2']; for(var i = 0; i < patterns.length; i++) { db.getCollectionNames().filter(function (collection) { return /patterns[i]-/.test(collection)}) } This does not work ! – Boat Jan 05 '21 at 10:07