利用MongoDB 在編程上帶來不少方便, 但稍一不慎就會令到結構變得難以複雜. 示範中會利用mongoDB 讀取collection 中的property name.
- 加入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 } );
- 設定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; }
- 存取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);
Leave a Reply