Brij Raj Singh - MSFT
Brij Raj Singh - MSFT

Reputation: 5113

mongo db get collections starting with

I have a number of collections by names like

app_users5473275725743
app_users5473275725746
app_users5473275725747
app_users5473275725748

I want to be able to find all the collections starting with name 'app_users', while db.getCollectionNames returns all the collection names.

Upvotes: 5

Views: 1630

Answers (2)

Lix
Lix

Reputation: 48006

You can use the filter function to extract only the relevant collection names:

var cols = db.getCollectionNames().filter( function( col ) { 
  return col.startsWith( "app_users" ) 
} )

This code will populate the cols variable with an array of collection names that start with app_users.

Reference: Array.prototype.filter()

Upvotes: 9

Mustafa Genç
Mustafa Genç

Reputation: 2579

db.getCollectionNames().forEach(function(collName) {
    if (collName.startsWith("app_users")) {
        print(collName);
    }
});

Upvotes: 4

Related Questions