zoukankan      html  css  js  c++  java
  • MongoDB 从入门到进阶

    [教程]MongoDB 从入门到进阶 (数据检索及统计 - 微博数据的整理)

    [教程]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;
    
            }
    复制代码

    GitHub地址: https://github.com/magicdict/MagicMongoDBTool

    联系方式 mynightelfplayer@hotmail.com

  • 相关阅读:
    【Unity Addressables】Addressables源码移植优化(一)
    Unity Addressable热更系统尝试(一)
    python自动化测试,下载文件然后进行查询判断并且删除(比较准确!可用于多个重复的文件)
    python自动化测试-切换至iframe的具体操作。
    python自动化测试-给标签的属性值进行赋值。
    如何区分前后端bug
    python字符串中获取数字
    安装Xshell遇到的问题: xshell启动遇到由于找不到mfc110.dll,无法继续执行代码的解决方法/产品运行所需的信息检索失败。请重新安装xshell
    python自动化测试,遇到selenium.common.exceptions.ElementClickInterceptedException: Message: Element错的解决方法
    在线正则表达式校验
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/2857174.html
Copyright © 2011-2022 走看看