In this article, we will see how to get list field names with their field types of collection in MongoDB. It contains two steps:
Step1: Write a function:
Lets create a function.
var fieldNames = function(schema, i, limit) { var i = (typeof i !== 'undefined') ? i : 1; var limit = (typeof limit !== 'undefined') ? limit : false; var type = ''; var array = false; for (key in schema) { type = typeof schema[key]; array = (schema[key] instanceof Array) ? true : false; if (type === 'object') { print(Array(i).join(' ') + key+' <'+((array) ? 'array' : type)+'>:'); schemafy(schema[key], i+1, array); } else { print(Array(i).join(' ') + key+' <'+type+'>'); } if (limit) { break; } } }
Step2: Apply the above function:
Lets switch to the database where collection exists.
use m201
Then run:
fieldNames(db.people.findOne())
Output:
_id