• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:9 mins read
You are currently viewing Get All Field Names in MongoDB

How to get all field names from the MongoDB collection? This article will mainly focus on getting the names of all keys also known as all field names in MongoDB and will explain different examples to do so.

Advertisements

The collection student is used in this article which is inserted with the following document containing various fields.


# Create Collection
db.student.insertMany([
      {  
         "firstName": "Jimmy",
         "lastName": "Dan",
         "age": 20,
         "marks": 90
      },
      {
         "firstName": "Ian",
         "lastName": "Wasely",
         "age": 17,
         "marks": 80
      }
   ]
)

1. Using findOne() to get All Field Names in MongoDB

To get all field names or names of all keys from the collection, use the findOne() along with the for loop. The findOne() returns only one document that meets the provided criteria. And extract the keys from the document by using for loop.


# Get all key names
Keys=db.student.findOne();
for (key in Keys){
 print(key);
}

Consider the following example where we use the findOne() method to retrieve a single document from the collection, and then iterate over the keys in the document using a for loop to get all field names. Then print the keys to the console using the print() method. The output shows all the fields of the document after executing the query.

Get All Field Names in MongoDB

More information about this method can be found here.

2. Using aggregate() method to get the names of keys

As we know, the aggregate() method is used to perform complex queries on a collection. Aggregation refers to the procedure of going through several phases with a huge collection of documents to process them. So, we can use the $project stage to retrieve the field names. The $project sends the documents with the specified fields to the very next pipeline stage.


# Using aggregate() method 
db.student.aggregate([
    { $project: { keys: { $objectToArray: "$$ROOT" } } },
    { $group: { _id: "$keys.k" } }
]).forEach(function(doc) { print(doc._id); });

Consider the query above where the aggregate() method is used in projects which further use the $objectToArray operator to convert each document in the collection into an array of key-value pairs. The $$ROOT variable represents the current document.

After that, the $group stage groups the documents together based on their keys. The _id field is set to $keys.k, which is the key name from the array produced in the previous stage. Finally, the forEach() method iterates over the results and prints out each unique key.

Thus, the output is retrieved with all the keys of the documents in the student collection.

Get Names of Keys in MongoDB

3. Using JavaScript to get field names in MongoDB

Moreover, to retrieve all keys or field names from a collection in MongoDB we can use JavaScript. Users can apply a JavaScript function to every document in a cursor by using the forEach() method.


# Using forEach() method
var Mykeys = [];
db.student.find().forEach(function(doc) {
    for(var key in doc) {
        if(Mykeys.indexOf(key) === -1) {
            Mykeys.push(key);
        }
    }
});
Mykeys.forEach(print);

Here, we have first used the forEach() method that is used to iterate over each document. Within the forEach() loop, another loop is used to iterate over each key in the current document. If the key is not already in the Mykeys array, it is added to the array using the push() method.

In the end, the forEach() method iterates again over the Mykeys array and prints out each key to the console. The output is a list of all the unique keys in the student collection.

get all field names in MongoDB

4. Using mapReduce() to Get All Field Names

In addition, we can use the mapReduce() method of MongoDB to get the name of all keys. In general, it performs a map function to each document in the collection and then reduces the results to a single output.

The emit(key,value) function call is an optional thing that allows the map function to generate output documents that link key and value.


# Using mapReduce() to get all field names
db.student.mapReduce(
    function() { for (var key in this) { emit(key, null); } },
    function(key, values) { return null; },
    { out: "Newkeys" }
);
db.Newkeys.find().forEach(function(doc) { print(doc._id); });

Consider the following query where we have to use the mapReduce() method to emit all the keys present in each document of the student collection and then reduce them to null values. All the documents are then retrieved by using the find() method on the Newkeys collection. The forEach() method is used to iterate over each document in the Newkeys collection and print out the _id field, which contains the key name. Hence, the unique keys are listed in the output below.

Get Names of Keys in MongoDB

5. Using $exists Operator

When you want to retrieve documents based on whether a field (given in the $exists query) contains or does not contain data, you use the $exists operator. The $exists command’s basis depends on Boolean values, which manage the output in accordance with the user’s requirements. To get the names of all the keys, we have an $exists operator which retrieves the specified keys with values if they exist in the collection.


# Using $exists operator
db.student.find({"age": {$exists: true}}, {"age": 1})

Consider the query is specified with the $exists operator with value set to true which matches all documents that have an age field. The projection object age:1 includes only the age field in the results. In the end, this query will return a cursor object that can be used to iterate over the results. Each document in the results will have only two fields: _id and age, where _id is the unique identifier for the document and age is the value of the age field. The expected output is listed with the keys _id and age along with their values.

Get Names of Keys in MongoDB

6. Conclusion

In conclusion, retrieving all the keys in a MongoDB collection can be achieved using various methods. By using these methods, we can easily retrieve all the unique field names in a collection.