How to list all field names in MongoDB?

To list all field names in MongoDB, you can use the db.collection.find() method and set the projection parameter to an empty document ({}). This will return all fields within the documents in the collection. Additionally, you can use the db.collection.distinct() method to list all the distinct field names in the collection.


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.

The following tutorials explain how to perform other common operations in MongoDB:

x