Home » MongoDB: How to List All Field Names

MongoDB: How to List All Field Names

by Erma Khan

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:

MongoDB: How to Rename Fields
MongoDB: How to Remove Fields
MongoDB: How to Add New Fields

Related Posts