Table of Contents
MongoDB is a NoSQL database system that stores data in the form of documents. Each document contains a set of key-value pairs, where the key represents the field name and the value represents the data stored in that field. In MongoDB, the field names can be chosen freely by the user and can vary for each document. Therefore, there is no fixed list of field names in MongoDB. However, some commonly used field names are “_id” for the unique identifier of the document, “createdAt” for the creation timestamp, “updatedAt” for the last update timestamp, and “type” for categorizing the data. Ultimately, the field names in MongoDB are highly customizable and can be tailored to fit the specific needs of the data being stored.
MongoDB: List All Field Names
You can use the following syntax to list all field names in a collection in MongoDB:
Object.keys(db.myCollection.findOne())
This particular example lists every field name in a collection titled myCollection.
The following example shows how to use this syntax in practice with a collection teams with the following documents:
db.teams.insertOne({team: "Mavs", points: 30, rebounds: 8, assists: 2})
db.teams.insertOne({team: "Mavs", points: 35, rebounds: 12, assists: 6})
db.teams.insertOne({team: "Spurs", points: 20, rebounds: 7, assists: 8})
db.teams.insertOne({team: "Spurs", points: 25, rebounds: 5, assists: 9})
db.teams.insertOne({team: "Spurs", points: 23, rebounds: 9, assists: 4})
Example: List All Field Names in MongoDB
The following code shows how to list all field names in the teams collection:
Object.keys(db.teams.findOne())This query returns the following documents:
[ '_id', 'team', 'points', 'rebounds', 'assists' ]
Notice that the list of field names also includes the _id field, which MongoDB automatically generates for each document.
Note: To list the field names in another collection, simply change the teams name to another name.
Additional Resources
The following tutorials explain how to perform other common operations in MongoDB:
Cite this article
stats writer (2024). What are all the field names in MongoDB?. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/what-are-all-the-field-names-in-mongodb/
stats writer. "What are all the field names in MongoDB?." PSYCHOLOGICAL SCALES, 30 Jun. 2024, https://scales.arabpsychology.com/stats/what-are-all-the-field-names-in-mongodb/.
stats writer. "What are all the field names in MongoDB?." PSYCHOLOGICAL SCALES, 2024. https://scales.arabpsychology.com/stats/what-are-all-the-field-names-in-mongodb/.
stats writer (2024) 'What are all the field names in MongoDB?', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/what-are-all-the-field-names-in-mongodb/.
[1] stats writer, "What are all the field names in MongoDB?," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, June, 2024.
stats writer. What are all the field names in MongoDB?. PSYCHOLOGICAL SCALES. 2024;vol(issue):pages.
