[教程]MongoDB 從入門到進階 (數據檢索及統計 - 微博數據的整理)
下載地址: http://www.wojilu.com/Forum1/Topic/4601
GitHub: https://github.com/magicdict/MagicMongoDBTool
這次講解一下MongoDB的數據統計能力。
作為統計數據,這里我采集了楊冪的微博上的粉絲作為實驗數據。由於最多只能一天采集5000個粉絲的資料,所以,數據也只有5000條。
同時,這些資料雖然來自於User這個類,但是沒有牽涉到層次結構,無法體會階層型數據庫的威力,也是蠻遺憾的。
下面的代碼是用來采集數據的。展示這段代碼,一來說明一下如何正確的使用新浪微博的API,二來說明一下,MongoDB就像一個ORM一樣,直接將對象保存到數據庫中了。
當然新浪微博的API你可以去這里下載, http://weibosdk.codeplex.com/
API函數有些蠻坑人的地方,雖然方法參數中,獲取粉絲資料數量可以是Int32,不過,你真的設置一個大於200的數字,程序會報錯,參數類型不匹配。
我原來以為真的是參數類型的問題,但是編譯沒有報錯。。。。最后發現,還有200的限制。。。。。既然你限制了,你就寫成Byte啊。。。坑爹。。。。
1 private void btnGetFollowers_Click(object sender, EventArgs e) 2 { 3 var Srv = SystemManager.GetCurrentServer(); 4 if (Srv != null) 5 { 6 var db = Srv.GetDatabase("SinaWeibo"); 7 var oauth = new NetDimension.Weibo.OAuth(txtAppKey.Text, txtAppSrect.Text); 8 bool result = oauth.ClientLogin(txtWeiBoUsr.Text, txtWeiBoPsw.Text); 9 if (result) //返回true成功 10 { 11 var Sina = new NetDimension.Weibo.Client(oauth); 12 var uid = Sina.API.Account.GetUID(); 13 var col = db.GetCollection(txtSupperStarID.Text + txtSupperStarName.Text + "(Followers)"); 14 int UserCount; 15 int TotalCount; 16 UserCount = 0; 17 TotalCount = 0; 18 19 NetDimension.Weibo.Entities.user.Collection followers; 20 do 21 { 22 followers = Sina.API.Friendships.Followers(txtSupperStarID.Text, "", 150, UserCount, true); 23 if (TotalCount == 0) 24 { 25 TotalCount = followers.TotalNumber; 26 } 27 foreach (var follow in followers.Users) 28 { 29 col.Insert(follow); 30 UserCount++; 31 } 32 } while (UserCount < TotalCount); 33 MessageBox.Show("OK"); 34 } 35 } 36 else { 37 MessageBox.Show("MongoDB Not Found"); 38 } 39 }
采集好的數據如圖所示:(雖然不是個人信息,還是打馬賽克吧)
[看看條數:聚合 Count]
5000條記錄。。。這個就不用解釋了吧。聚合的Count,就是條數統計
Collection對象有Count方法,直接調用就可以了。當然,Count支持條件過濾。
if (Query.QueryConditionList.Count == 0 || !IsUseFilter) { MyMessageBox.ShowEasyMessage("Count", "Count Result : " + SystemManager.GetCurrentCollection().Count().ToString()); } else { MongoDB.Driver.IMongoQuery mQuery = MongoDBHelper.GetQuery(Query.QueryConditionList); MyMessageBox.ShowMessage("Count", "Count[With DataView Filter]:" + SystemManager.GetCurrentCollection().Count(mQuery).ToString(), mQuery.ToString(), true); }
[看看有多少地區的人玩微博:聚合 Distinct]
Distinct也是比較常用的功能,同樣字段的記錄,只算一條。例如,我們想看看,到底多少地方的人玩微博,我們可以對用戶的所在省份進行Distinct操作。
一共出現36個省份的編號。100代表的是未知。31代表上海,11代表北京
BsonArray ResultArray = (BsonArray)SystemManager.GetCurrentCollection().Distinct(strKey, MongoDBHelper.GetQuery(DistinctConditionList));
[看看每個省份玩微博的人數:聚合 Group]
有興趣玩NoSQL的人,數據庫都不會差,Group是干什么的,大家都知道。OK,
對於省份Group一下,然后看看Count數字吧。
由於工具還沒有完成,現在暫時只提供(內置了)Count的Group功能,當然你也可以自己修改Reduce和InitFields來獲得其他結果。
【高級功能MapReduce】
數據太少,用MapReduce。Map函數是分散給各個不同的數據實例並行做的。Reduce函數則是將各個Map函數的結果進行最后的合並統計。
官方的資料:http://docs.mongodb.org/manual/applications/map-reduce/
MapReduce的東西,以后會拿出來作為單獨的一個主題,這里就展示一下。。。
【Query:我只想看姓名和城市和性別】
這么多數據字段,眼睛看花了,我只想看名字和城市,還有性別(找妹紙啊)。。。。。。
呵呵,上海的妹子。。。。。
繼續打馬賽克:500人里面,女性,省份是31的,一共137人。。。。。
靈活運用查詢,一切盡在掌握。
核心代碼:
FindAs方法,支持查詢條件,顯示字段,排序,Skip指定記錄數,抽出記錄數。
官方資料:http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-FindandFindAsmethods
/// <summary> /// 獲得展示數據 /// </summary> /// <param name="CurrentDataViewInfo"></param> public static List<BsonDocument> GetDataList(ref DataViewInfo CurrentDataViewInfo) { String collectionPath = CurrentDataViewInfo.strDBTag.Split(":".ToCharArray())[1]; String[] cp = collectionPath.Split("/".ToCharArray()); MongoServer mServer = SystemManager.GetCurrentServer(); MongoCollection mongoCol = mServer.GetDatabase(cp[(int)PathLv.DatabaseLV]).GetCollection(cp[(int)PathLv.CollectionLV]); MongoCursor<BsonDocument> cursor; //Query condition: if (CurrentDataViewInfo.IsUseFilter) { cursor = mongoCol.FindAs<BsonDocument>(GetQuery(CurrentDataViewInfo.mDataFilter.QueryConditionList)) .SetSkip(CurrentDataViewInfo.SkipCnt) .SetFields(GetOutputFields(CurrentDataViewInfo.mDataFilter.QueryFieldList)) .SetSortOrder(GetSort(CurrentDataViewInfo.mDataFilter.QueryFieldList)) .SetLimit(CurrentDataViewInfo.LimitCnt); } else { cursor = mongoCol.FindAllAs<BsonDocument>() .SetSkip(CurrentDataViewInfo.SkipCnt) .SetLimit(CurrentDataViewInfo.LimitCnt); } if (cursor.Query != null) { CurrentDataViewInfo.Query = cursor.Query.ToJson(SystemManager.JsonWriterSettings); } else { CurrentDataViewInfo.Query = String.Empty; } CurrentDataViewInfo.Explain = cursor.Explain().ToJson(SystemManager.JsonWriterSettings); List<BsonDocument> dataList = cursor.ToList(); if (CurrentDataViewInfo.SkipCnt == 0) { if (CurrentDataViewInfo.IsUseFilter) { //感謝cnblogs.com 網友Shadower CurrentDataViewInfo.CurrentCollectionTotalCnt = (int)mongoCol.Count(GetQuery(CurrentDataViewInfo.mDataFilter.QueryConditionList)); } else { CurrentDataViewInfo.CurrentCollectionTotalCnt = (int)mongoCol.Count(); } } SetPageEnable(ref CurrentDataViewInfo); return dataList; }