First thing first: MongoDB is schemaless and does not have tables. In MongoDB, each collection can have very different types of items. You can store two completely different items in the same collection. However, if you are sure that it will have same structure you can use some trick to get the data.
Get all the field names using below code:
db.collection.aggregate([
{
$project: {
data: {
$objectToArray: "$$ROOT"
}
}
},
{
$project: {
data: "$data.k"
}
},
{
$unwind: "$data"
},
{
$group: {
_id: null,
keys: {
$addToSet: "$data"
}
}
},
{
$unwind: "$keys"
},
{
$project: {
_id: 0,
key: "$keys"
}
}
])
Which gives results as:
[
{
"key": "egg"
},
{
"key": "type"
},
{
"key": "hello"
},
{
"key": "_id"
}
]
You can use these results to get type of the each field using aggregate:
db.Garments.aggregate(
{ "$project": { "fieldType": { "$type": "$_id" } } } //use fieldName from previous results
)
which returns something like:
{
"_id" : ObjectId("4c0ec11e8fd2e65c0b010000"),
"fieldType" : "string"
}
There are other ways using Map-Reduce functions, one example is here: Using map/reduce for mapping the properties in a collection