Sandi
Sandi

Reputation: 11

MongoDB JSON structure

Is there any way to determine the structure of a collection in mongodb without the data ? Suppose I have a collection with multiple documents. Let's assume the first 10 documents have 10 attributes and the next 10 have 12 (10 + 2 new) attributes. And all I am looking for is the generic json layout for the documents in the collection without the data. This is equivalent to a table description (desc table_name in Oracle or sp_help table_name in SQL Server) in RDBMS. I would really appreciate if any of you have tried this before.

Upvotes: 0

Views: 207

Answers (2)

whaley
whaley

Reputation: 16265

Edit: You may want to look at this tool https://github.com/variety/variety


There is no such command as collections in mongo must support completely heterogenous set of documents. Though it's not good design whatsoever, the following is completely legal and supported:

> db.foo.insert({"a" : 1})
> db.foo.insert({"a" : "a string"})
> db.foo.insert({"b" : []})
> db.foo.find().pretty()
{ "_id" : ObjectId("51c19d7a3997c43593afcfed"), "a" : 1 }
{ "_id" : ObjectId("51c19d813997c43593afcfee"), "a" : "a string" }
{ "_id" : ObjectId("51c19d8a3997c43593afcfef"), "b" : [ ] }

The only way such a behavior you wish for would work is if it returned "_id" as the lone common field, which you already know is a common field. Sure, two fields have "a", but the value of the key "a" may be of different types.

The best you can hope for is some solution like @Munim suggested which hypothetically looks like the following.

function common_keys(coll) {
  function array_intersection(a,b) {
    return a.filter(function(n) {
      if(b.indexOf(n) == -1)
        return false;
      return true;
    });
  }

  var cur = coll.find();
  var common_keys_in_collection = Object.keys(cur.next());

  while (cur.hasNext()) {
    var document_keys = Object.keys(cur.next())
    common_keys_in_collection = array_intersection(common_keys_in_collection, document_keys)
  }

  return common_keys_in_collection
}

Note that the example code does not handle deeply nested structures, so this won't find common keys in subdocuments.

Upvotes: 1

Munim
Munim

Reputation: 6520

I don't think there is any one command to do it. But what you can do is write a program which fetches all the documents in the collection, loop through each document, and add the keys for each in your schema structure.

Upvotes: 0

Related Questions