Find all collections in MongoDB with specific field?


Let us implement the above syntax in order to find all documents in MongoDB with field name “StudentFirstName”. The query is as follows −

> 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

Let us verify the removeKeyFieldsDemo collection has field with name “StudentFirstName” or not. Following is the query −

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

This will produce the following output displaying the StudentFirstName field exist −

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

Updated on: 30-Jul-2019

793 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements