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
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.
