/// <summary>
        /// 添加索引
        /// </summary>
        /// <param name="AscendingKey"></param>
        /// <param name="DescendingKey"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public static Boolean CreateMongoIndex(String[] AscendingKey, String[] DescendingKey, IndexOptionsBuilder option)
        {
            MongoCollection  mongoCol  = SystemManager.GetCurrentCollection();
            IndexKeysBuilder indexkeys = new IndexKeysBuilder();

            indexkeys.Ascending(AscendingKey);
            indexkeys.Descending(DescendingKey);
            mongoCol.CreateIndex(indexkeys, option);
            return(true);
        }
        /// <summary>
        ///     当前对象的MONGO命令
        /// </summary>
        /// <param name="mMongoCommand">命令对象</param>
        /// <param name="ShowMsgBox"></param>
        /// <returns></returns>
        public static CommandResult ExecuteMongoCommand(MongoCommand mMongoCommand, Boolean ShowMsgBox = true)
        {
            var ResultCommandList = new List <CommandResult>();

            var mCommandResult = new CommandResult(new BsonDocument());

            try
            {
                switch (mMongoCommand.RunLevel)
                {
                case MongoDbHelper.PathLv.CollectionLv:
                    if (String.IsNullOrEmpty(mMongoCommand.CommandString))
                    {
                        mCommandResult = ExecuteMongoColCommand(mMongoCommand.cmdDocument,
                                                                SystemManager.GetCurrentCollection());
                    }
                    else
                    {
                        mCommandResult = ExecuteMongoColCommand(mMongoCommand.CommandString,
                                                                SystemManager.GetCurrentCollection());
                    }
                    break;

                case MongoDbHelper.PathLv.DatabaseLv:
                    mCommandResult = ExecuteMongoDBCommand(mMongoCommand.cmdDocument,
                                                           SystemManager.GetCurrentDataBase());
                    break;

                case MongoDbHelper.PathLv.InstanceLv:
                    mCommandResult = ExecuteMongoSvrCommand(mMongoCommand.cmdDocument,
                                                            SystemManager.GetCurrentServer());
                    break;

                default:
                    break;
                }
                ResultCommandList.Add(mCommandResult);
                if (ShowMsgBox)
                {
                    MyMessageBox.ShowMessage(mMongoCommand.CommandString, mMongoCommand.CommandString + " Result",
                                             MongoDbHelper.ConvertCommandResultlstToString(ResultCommandList), true);
                }
            }
            catch (IOException ex)
            {
                SystemManager.ExceptionDeal(ex, mMongoCommand.CommandString,
                                            "IOException,Try to set Socket TimeOut more long at connection config");
            }
            catch (Exception ex)
            {
                SystemManager.ExceptionDeal(ex, mMongoCommand.CommandString);
            }

            return(mCommandResult);
        }
        /// <summary>
        /// Drop Element
        /// </summary>
        /// <param name="BaseDoc"></param>
        /// <param name="ElementPath"></param>
        public static void DropElement(String ElementPath, BsonElement El)
        {
            BsonDocument BaseDoc = SystemManager.CurrentDocument;
            BsonValue    t       = GetLastParentDocument(BaseDoc, ElementPath, false);

            if (t.IsBsonDocument)
            {
                t.AsBsonDocument.Remove(El.Name);
            }
            SystemManager.GetCurrentCollection().Save(BaseDoc);
        }
        /// <summary>
        /// 删除索引[KEY_ID]以外
        /// </summary>
        /// <param name="indexName"></param>
        /// <returns></returns>
        public static Boolean DropMongoIndex(String indexName)
        {
            if (indexName == KEY_ID)
            {
                return(false);
            }
            MongoCollection mongoCol = SystemManager.GetCurrentCollection();

            if (mongoCol.IndexExistsByName(indexName))
            {
                mongoCol.DropIndexByName(indexName);
            }
            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="ElementPath"></param>
        public static void PasteValue(String ElementPath)
        {
            BsonDocument BaseDoc = SystemManager.CurrentDocument;
            BsonValue    t       = GetLastParentDocument(BaseDoc, ElementPath, true);

            if (t.IsBsonArray)
            {
                t.AsBsonArray.Insert(t.AsBsonArray.Count, (BsonValue)_ClipElement);
            }
            if (!SystemManager.GetCurrentCollection().IsCapped())
            {
                SystemManager.GetCurrentCollection().Save(BaseDoc);
            }
        }
        /// <summary>
        /// Modify A Value of Array
        /// </summary>
        /// <param name="ElementPath"></param>
        /// <param name="NewValue"></param>
        /// <param name="ValueIndex"></param>
        /// <param name="El"></param>
        public static void ModifyArrayValue(String ElementPath, BsonValue NewValue, int ValueIndex)
        {
            BsonDocument BaseDoc = SystemManager.CurrentDocument;
            BsonValue    t       = GetLastParentDocument(BaseDoc, ElementPath, false);

            if (t.IsBsonArray)
            {
                t.AsBsonArray[ValueIndex] = NewValue;
            }
            if (!SystemManager.GetCurrentCollection().IsCapped())
            {
                SystemManager.GetCurrentCollection().Save(BaseDoc);
            }
        }
        /// <summary>
        /// Modify Element
        /// </summary>
        /// <param name="ElementPath"></param>
        /// <param name="NewValue"></param>
        /// <param name="ValueIndex"></param>
        /// <param name="El"></param>
        public static void ModifyElement(String ElementPath, BsonValue NewValue, BsonElement El)
        {
            BsonDocument BaseDoc = SystemManager.CurrentDocument;
            BsonValue    t       = GetLastParentDocument(BaseDoc, ElementPath, false);

            if (t.IsBsonDocument)
            {
                t.AsBsonDocument.GetElement(El.Name).Value = NewValue;
            }
            if (!SystemManager.GetCurrentCollection().IsCapped())
            {
                SystemManager.GetCurrentCollection().Save(BaseDoc);
            }
        }
        /// <summary>
        /// 添加索引
        /// </summary>
        /// <param name="AscendingKey"></param>
        /// <param name="DescendingKey"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public static Boolean CreateMongoIndex(String[] AscendingKey, String[] DescendingKey, String GeoSpatialKey, IndexOptionsBuilder option)
        {
            MongoCollection  mongoCol  = SystemManager.GetCurrentCollection();
            IndexKeysBuilder indexkeys = new IndexKeysBuilder();

            if (!String.IsNullOrEmpty(GeoSpatialKey))
            {
                indexkeys.GeoSpatial(GeoSpatialKey);
            }
            indexkeys.Ascending(AscendingKey);
            indexkeys.Descending(DescendingKey);
            mongoCol.EnsureIndex(indexkeys, option);
            return(true);
        }
        public static void ExportToFile(DataViewInfo CurrentDataViewInfo, String ExcelFileName, ExportType exportType)
        {
            MongoCollection mongoCol;

            if (CurrentDataViewInfo == null)
            {
                mongoCol = SystemManager.GetCurrentCollection();
            }
            else
            {
                String      collectionPath = CurrentDataViewInfo.strDBTag.Split(":".ToCharArray())[1];
                String[]    cp             = collectionPath.Split("/".ToCharArray());
                MongoServer mServer        = SystemManager.GetCurrentServer();
                mongoCol = mServer.GetDatabase(cp[(int)PathLv.DatabaseLv]).GetCollection(cp[(int)PathLv.CollectionLv]);
            }
            MongoCursor <BsonDocument> cursor;

            //Query condition:
            if (CurrentDataViewInfo != null && CurrentDataViewInfo.IsUseFilter)
            {
                cursor = mongoCol.FindAs <BsonDocument>(QueryHelper.GetQuery(CurrentDataViewInfo.mDataFilter.QueryConditionList))
                         .SetFields(QueryHelper.GetOutputFields(CurrentDataViewInfo.mDataFilter.QueryFieldList))
                         .SetSortOrder(QueryHelper.GetSort(CurrentDataViewInfo.mDataFilter.QueryFieldList));
            }
            else
            {
                cursor = mongoCol.FindAllAs <BsonDocument>();
            }
            List <BsonDocument> dataList = cursor.ToList();

            switch (exportType)
            {
            case ExportType.Excel:
                //ExportToExcel(dataList, ExcelFileName);
                GC.Collect();
                break;

            case ExportType.Text:
                ExportToJson(dataList, ExcelFileName);
                break;

            case ExportType.Xml:
                break;

            default:
                break;
            }
            OnActionDone(new ActionDoneEventArgs(" Completeed "));
        }
 /// <summary>
 /// 执行聚合
 /// </summary>
 /// <param name="AggregateDoc"></param>
 /// <returns></returns>
 public static CommandResult Aggregate(BsonArray AggregateDoc)
 {
     //db.runCommand( { aggregate: "people", pipeline: [<pipeline>] } )
     try
     {
         CommandDocument agg = new CommandDocument();
         agg.Add(new BsonElement("aggregate", new BsonString(SystemManager.GetCurrentCollection().Name)));
         agg.Add(new BsonElement("pipeline", AggregateDoc));
         MongoCommand Aggregate_Command = new MongoCommand(agg, PathLv.DatabaseLV);
         return(ExecuteMongoCommand(Aggregate_Command, false));
     }
     catch (Exception ex)
     {
         SystemManager.ExceptionDeal(ex);
         return(new CommandResult(new BsonDocument()));
     }
 }
示例#11
0
        /// <summary>
        /// 当前对象的MONGO命令
        /// </summary>
        /// <param name="cmd">命令对象</param>
        /// <returns></returns>
        public static void ExecuteMongoCommand(MongoCommand cmd)
        {
            var Command = new CommandDocument {
                { cmd.CommandString, 1 }
            };
            List <CommandResult> ResultCommandList = new List <CommandResult>();

            CommandResult rtn = new CommandResult();

            try
            {
                switch (cmd.RunLevel)
                {
                case PathLv.CollectionLV:
                    rtn = ExecuteMongoColCommand(cmd.CommandString, SystemManager.GetCurrentCollection());
                    break;

                case PathLv.DatabaseLV:
                    rtn = ExecuteMongoDBCommand(Command, SystemManager.GetCurrentDataBase());
                    break;

                case PathLv.ServerLV:
                    rtn = ExecuteMongoSvrCommand(Command, SystemManager.GetCurrentServer());
                    break;

                default:
                    break;
                }
                ResultCommandList.Add(rtn);
                MyMessageBox.ShowMessage(cmd.CommandString, cmd.CommandString + " Result", MongoDBHelper.ConvertCommandResultlstToString(ResultCommandList), true);
            }
            catch (System.IO.IOException ex)
            {
                MyMessageBox.ShowMessage(cmd.CommandString, "IOException,Try to set Socket TimeOut more long at connection config", ex.ToString(), true);
            }
            catch (Exception ex)
            {
                SystemManager.ExceptionDeal(ex, cmd.CommandString);
            }
        }
        //http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-UsageandRestrictions
        //Usage and Restrictions Of capped collection.
        //You may insert new documents in the capped collection.
        //You may update the existing documents in the collection. However, the documents must not grow in size. If they do, the update will fail. Note if you are performing updates, you will likely want to declare an appropriate index (given there is no _id index for capped collections by default).
        //The database does not allow deleting documents from a capped collection. Use the drop() method to remove all rows from the collection. (After the drop you must explicitly recreate the collection.)
        //Capped collection are not shard-able.

        /// <summary>
        /// Paste
        /// </summary>
        /// <param name="ElementPath"></param>
        public static String PasteElement(String ElementPath)
        {
            BsonDocument BaseDoc = SystemManager.CurrentDocument;
            BsonValue    t       = GetLastParentDocument(BaseDoc, ElementPath, true);

            if (t.IsBsonDocument)
            {
                try
                {
                    t.AsBsonDocument.InsertAt(t.AsBsonDocument.ElementCount, (BsonElement)_ClipElement);
                }
                catch (InvalidOperationException ex)
                {
                    return(ex.Message);
                }
            }
            if (!SystemManager.GetCurrentCollection().IsCapped())
            {
                SystemManager.GetCurrentCollection().Save(BaseDoc);
            }
            return(String.Empty);
        }
        /// <summary>
        /// 将数据放入ListView中进行展示
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="lstData"></param>
        /// <param name="dataList"></param>
        public static void FillDataToListView(String collectionName, ListView lstData, List <BsonDocument> dataList)
        {
            lstData.Clear();
            lstData.SmallImageList = null;
            switch (collectionName)
            {
            case COLLECTION_NAME_GFS_FILES:
                SetGridFileToListView(dataList, lstData);
                break;

            case COLLECTION_NAME_USER:
                SetUserListToListView(dataList, lstData);
                break;

            default:
                List <String> _columnlist = new List <String>();
                //可以让_id 不在第一位,昏过去了,很多逻辑需要调整
                bool isSystem = IsSystemCollection(SystemManager.GetCurrentCollection());
                if (!isSystem)
                {
                    _columnlist.Add(KEY_ID);
                    lstData.Columns.Add(KEY_ID);
                }
                foreach (BsonDocument docItem in dataList)
                {
                    ListViewItem lstItem = new ListViewItem();
                    foreach (String item in docItem.Names)
                    {
                        if (!_columnlist.Contains(item))
                        {
                            _columnlist.Add(item);
                            lstData.Columns.Add(item);
                        }
                    }

                    //Key:_id
                    if (!isSystem)
                    {
                        BsonElement id;
                        docItem.TryGetElement(KEY_ID, out id);
                        if (id != null)
                        {
                            lstItem.Text = docItem.GetValue(KEY_ID).ToString();
                            //这里保存真实的主Key数据,删除的时候使用
                            lstItem.Tag = docItem.GetValue(KEY_ID);
                        }
                        else
                        {
                            lstItem.Text = "[Empty]";
                            lstItem.Tag  = docItem.GetElement(0).Value;
                        }
                    }
                    else
                    {
                        lstItem.Text = docItem.GetValue(_columnlist[0].ToString()).ToString();
                    }
                    //OtherItems
                    for (int i = isSystem ? 1 : 0; i < _columnlist.Count; i++)
                    {
                        if (_columnlist[i].ToString() == KEY_ID)
                        {
                            continue;
                        }
                        BsonValue val;
                        docItem.TryGetValue(_columnlist[i].ToString(), out val);
                        if (val == null)
                        {
                            lstItem.SubItems.Add("");
                        }
                        else
                        {
                            lstItem.SubItems.Add(ConvertToString(val));
                        }
                    }
                    lstData.Items.Add(lstItem);
                }
                break;
            }
        }
        //http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart(旧网址)
        //http://docs.mongodb.org/manual/reference/sql-comparison/

        /// <summary>
        /// Convert Query Sql To DataFilter
        /// </summary>
        /// <param name="Sql"></param>
        /// <returns></returns>
        public static DataFilter ConvertQuerySql(String Sql)
        {
            DataFilter rtnQuery = new DataFilter();

            Sql = Sql.Trim();
            //引号中的空格用&nbsp;代替,引号以外的东西小写
            Sql = Regular(Sql);
            //先将字符串里面的空格统一成单个空格
            //Select    A,B  From   C ->
            //Select A,B From C
            while (Sql.Contains("  "))
            {
                Sql = Sql.Replace("  ", " ");
            }
            //找出Select ,From , Group
            String[] SqlToken = Sql.Split(" ".ToCharArray());

            int SelectStartIndex  = -1;
            int FromStartIndex    = -1;
            int WhereStartIndex   = -1;
            int GroupByStartIndex = -1;
            int OrderByStartIndex = -1;

            for (int i = 0; i < SqlToken.Length; i++)
            {
                switch (SqlToken[i].ToLower())
                {
                case "select":
                    SelectStartIndex = i;
                    break;

                case "from":
                    FromStartIndex = i;
                    break;

                case "where":
                    WhereStartIndex = i;
                    break;

                case "group":
                    GroupByStartIndex = i;
                    break;

                case "order":
                    OrderByStartIndex = i;
                    break;

                default:
                    break;
                }
            }

            String[] KeyWords = new String[] { "select", "from", "where", "group", "order" };

            //From - > CollectionName
            String          strFrom = GetKeyContent(FromStartIndex, SqlToken, KeyWords);
            MongoCollection mongoCol;

            //if ((strFrom != String.Empty) & SystemManager.GetCurrentDataBase().CollectionExists(strFrom))
            //{
            //    mongoCol = SystemManager.GetCurrentDataBase().GetCollection(strFrom);
            //}
            //else
            //{
            //    return null;
            //}
            //From:由于当前肯定是从固定表里面取数据
            mongoCol = SystemManager.GetCurrentCollection();

            //Select 设定 必须项
            //Select - > FieldList
            String strSelect = GetKeyContent(SelectStartIndex, SqlToken, KeyWords);

            if (strSelect == String.Empty)
            {
                return(null);
            }
            List <String> ColumnNameLst = MongoDBHelper.GetCollectionSchame(mongoCol);

            if (strSelect == "*")
            {
                //Select *
                foreach (String item in ColumnNameLst)
                {
                    DataFilter.QueryFieldItem field = new DataFilter.QueryFieldItem();
                    field.ColName  = item;
                    field.IsShow   = true;
                    field.sortType = DataFilter.SortType.NoSort;
                    rtnQuery.QueryFieldList.Add(field);
                }
            }
            else
            {
                //Select A,B,C
                foreach (String item in strSelect.Split(",".ToCharArray()))
                {
                    DataFilter.QueryFieldItem field = new DataFilter.QueryFieldItem();
                    field.ColName  = item;
                    field.IsShow   = true;
                    field.sortType = DataFilter.SortType.NoSort;
                    rtnQuery.QueryFieldList.Add(field);
                }
            }

            //Where 设定,可选项
            String strWhere = GetKeyContent(WhereStartIndex, SqlToken, KeyWords);

            if (strWhere != String.Empty)
            {
                rtnQuery.QueryConditionList = SetQueryCondition(strWhere, ColumnNameLst);
            }

            //Order 设定,可选项
            String strOrder = GetKeyContent(OrderByStartIndex, SqlToken, KeyWords);

            if (strOrder != String.Empty)
            {
                SetQueryOrder(rtnQuery, strOrder);
            }


            //Group 设定,可选项
            String strGroup = GetKeyContent(GroupByStartIndex, SqlToken, KeyWords);

            if (strGroup != String.Empty)
            {
                //TODO:Group
            }

            return(rtnQuery);
        }