Find all collections in MongoDB with specific field?

To find all collections in MongoDB that contain documents with a specific field, use getCollectionNames() combined with the $exists operator to check for field presence across all collections in the database.

Syntax

db.getCollectionNames().forEach(function(collectionName) {
    var count = db[collectionName].find({"fieldName": {$exists: true}}).count();
    if (count > 0) {
        print(collectionName);
    }
});

Example: Find Collections with "StudentFirstName" Field

The following query searches all collections for documents containing the "StudentFirstName" field ?

db.getCollectionNames().forEach(function(myCollectionName) {
    var frequency = db[myCollectionName].find({"StudentFirstName": {$exists: true}}).count();
    if (frequency > 0) {
        print(myCollectionName);
    }
});

This will produce the following output ?

multiDimensionalArrayProjection
removeKeyFieldsDemo
stringOrIntegerQueryDemo

Verify Field Existence

Let us verify that the removeKeyFieldsDemo collection has the "StudentFirstName" field ?

db.removeKeyFieldsDemo.find({"StudentFirstName": {$exists: true}});

This will produce the following output displaying documents with the StudentFirstName field ?

{ "_id" : ObjectId("5cc6c8289cb58ca2b005e672"), "StudentFirstName" : "John", "StudentLastName" : "Doe" }
{ "_id" : ObjectId("5cc6c8359cb58ca2b005e673"), "StudentFirstName" : "John", "StudentLastName" : "Smith" }

Conclusion

Use getCollectionNames().forEach() with $exists to efficiently scan all collections for specific fields. This method helps identify which collections contain the required field structure across your entire database.

Updated on: 2026-03-15T00:56:04+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements