1

I need an array containing my MongoDB database collection and their fields with data type.

array would be like this :

data table array

I know in SQL server it is possible to access table fields information with INFORMATION_SCHEMA but I don't know how it is in MongoDB.

Thanks a lot.

Blue Moon
  • 411
  • 7
  • 20

1 Answers1

0

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

ersnh
  • 522
  • 1
  • 8
  • 20