[MongoDB] 顯示collection 內的column

利用MongoDB 在編程上帶來不少方便, 但稍一不慎就會令到結構變得難以複雜. 示範中會利用mongoDB 讀取collection 中的property name.

  1. 加入Function isArray() 及m_sub() 作檢查Array 及recursive load.
    isArray = function (v) {
      return v && typeof v === 'object' && typeof v.length === 'number' && !(v.propertyIsEnumerable('length'));
    }
    
    m_sub = function(base, value){
      for(var key in value) {
        if(key != "_id") { 
            emit(base + "." + key, null);
        if( isArray(value[key]) || typeof value[key] == 'object'){
          m_sub(base + "." + key, value[key]);
        }
    }
      }
    }
    
    db.system.js.save( { _id : "isArray", value : isArray } );
    db.system.js.save( { _id : "m_sub", value : m_sub } );
    
  2.  設定map reduce 以決定存取資料及filter 設定.
    map = function(){
      for(var key in this) {
        emit(key, null);
        if( isArray(this[key]) || typeof this[key] == 'object'){
          m_sub(key, this[key]);
        }
      }
    }
    
    reduce = function(key, stuff){ return null; }
  3. 存取collection.
    var collectionName="<<Collection Name>>";
    var mr = db.runCommand({
        "mapreduce" : collectionName, 
        "map" : map, 
        "reduce" : reduce,
        "out": "things" + "_keys"});
    var result=db[mr.result].distinct("_id");
    print(result);

     

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.