MongoDB: How to 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:

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

Featured Posts

2 Replies to “MongoDB: How to List All Field Names”

  1. If you have a collection that has inconsistent fields (e.g. using “pts” instead of “points” for the points field name on some documents, both of these fields do not get returned. Only one – whichever one the findOne uses. So it doesn’t seem you can use this command syntax to gather all fieldnames used in a collection. You can only to use it get the field names for one sample of the collection. Or am I missing something?

  2. This is inaccurate. If other documents have more fields than the one fetched, they will not show up. So, this will not return ALL possible fields for a colllection

Leave a Reply

Your email address will not be published. Required fields are marked *