6 C
London
Tuesday, March 11, 2025
HomeSoftware TutorialsMongoDBMongoDB: How to List All Field Names

MongoDB: How to List All Field Names

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories