/// <summary> /// 数据库分片 /// </summary> /// <param name="routeSvr"></param> /// <param name="shardingDB"></param> /// <returns></returns> public static CommandResult EnableSharding(MongoServer routeSvr, String shardingDB) { CommandDocument mongoCmd = new CommandDocument(); mongoCmd = new CommandDocument(); mongoCmd.Add("enablesharding", shardingDB); return ExecuteMongoCommand(mongoCmd, routeSvr); }
/// <summary> /// </summary> /// <param name="trvSvrStatus"></param> /// <param name="mongoConnClientLst"></param> public static void FillClientStatusToList(CtlTreeViewColumns trvSvrStatus, Dictionary<string, MongoClient> mongoConnClientLst) { var srvDocList = new List<BsonDocument>(); foreach (var mongoSvrKey in mongoConnClientLst.Keys) { try { var mongoClient = mongoConnClientLst[mongoSvrKey]; //flydreamer提供的代码 // 感谢 魏琼东 的Bug信息,一些命令必须以Admin执行 if (RuntimeMongoDbContext.GetServerConfigBySvrPath(mongoSvrKey).LoginAsAdmin) { var adminDb = mongoClient.GetDatabase(ConstMgr.DatabaseNameAdmin); //Can't Convert IMongoDB To MongoDB var command = new CommandDocument {{CommandHelper.ServerStatusCommand.CommandString, 1}}; var serverStatusDoc = CommandHelper.ExecuteMongoDBCommand(command, adminDb).Response; srvDocList.Add(serverStatusDoc); } } catch (Exception ex) { Utility.ExceptionDeal(ex); } } UiHelper.FillDataToTreeView("Server Status", trvSvrStatus, srvDocList, 0); //打开第一层 foreach (TreeNode item in trvSvrStatus.DatatreeView.Nodes) { item.Expand(); } }
public void TestCodeMissing() { var command = new CommandDocument("invalid", 1); var document = new BsonDocument(); var result = new CommandResult(command, document); Assert.IsFalse(result.Code.HasValue); }
/// 注意:有些命令可能只能用在mongos上面,例如addshard /// <summary> /// 使用Shell Helper命令 /// </summary> /// <param name="JsShell"></param> /// <param name="mongoSvr"></param> /// <returns></returns> public static CommandResult ExecuteJsShell(String JsShell, MongoServer mongoSvr) { var ShellCmd = new BsonDocument {{"$eval", new BsonJavaScript(JsShell)}, {"nolock", true}}; //必须nolock var mongoCmd = new CommandDocument(); mongoCmd.AddRange(ShellCmd); return ExecuteMongoSvrCommand(mongoCmd, mongoSvr); }
public void TestCode() { var command = new CommandDocument("invalid", 1); var document = new BsonDocument("code", 18); var result = new CommandResult(command, document); Assert.IsTrue(result.Code.HasValue); Assert.AreEqual(18, result.Code); }
/// <summary> /// 使用Shell Helper命令 /// </summary> /// <param name="JsShell"></param> /// <param name="mongoSvr"></param> /// <returns></returns> public static CommandResult ExecuteJsShell(String JsShell, MongoServer mongoSvr) { BsonDocument cmd = new BsonDocument(); cmd.Add("$eval", new BsonJavaScript(JsShell)); //必须nolock cmd.Add("nolock", true); CommandDocument mongoCmd = new CommandDocument() { cmd }; return ExecuteMongoCommand(mongoCmd, mongoSvr); }
/// <summary> /// 全文检索功能 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSearch_Click(object sender, EventArgs e) { var textSearchCommand = new CommandDocument { { "text", SystemManager.GetCurrentCollection().Name }, { "search", txtKey.Text } }; CommandResult SearchResult = SystemManager.GetCurrentCollection().Database.RunCommand(textSearchCommand); MongoDBHelper.FillDataToTreeView("MapReduce Result", trvResult, SearchResult.Response); }
public void TestOkMissing() { var command = new CommandDocument("invalid", true); var document = new BsonDocument(); var result = new CommandResult(command, document); try { var dummy = result.Ok; } catch (MongoCommandException ex) { Assert.IsTrue(ex.Message.StartsWith("Command 'invalid' failed: response has no ok element (response: ")); } }
/// <summary> /// 执行聚合 /// </summary> /// <param name="aggregateDoc"></param> /// <returns></returns> /// <param name="collectionName"></param> public static CommandResult Aggregate(BsonArray aggregateDoc, string collectionName) { //db.runCommand( { aggregate: "people", pipeline: [<pipeline>] } ) var aggrCmd = new CommandDocument { new BsonElement("aggregate", new BsonString(collectionName)), new BsonElement("pipeline", aggregateDoc) }; var aggregateCommand = new MongoCommand(aggrCmd, EnumMgr.PathLevel.Database); return ExecuteMongoCommand(aggregateCommand); }
/// <summary> /// 执行Count(指定路劲) /// </summary> /// <param name="QueryDoc"></param> /// <param name="databaseName"></param> /// <param name="collectionName"></param> /// <returns></returns> public static CommandResult Count(BsonDocument QueryDoc, string databaseName, string collectionName) { //db.runCommand( { aggregate: "people", pipeline: [<pipeline>] } ) var aggrCmd = new CommandDocument { new BsonElement("count", new BsonString(collectionName)), new BsonElement("query", QueryDoc) }; var aggregateCommand = new MongoCommand(aggrCmd, EnumMgr.PathLevel.Database, databaseName); return ExecuteMongoCommand(aggregateCommand); }
public void TestMaxMessageLengthWhenNotServerSuppliedUsesMaxBsonObjectSizeWhenLargerThanMongoDefaults() { var command = new CommandDocument("ismaster", 1); var document = new BsonDocument { { "ok", 1 }, { "maxBsonObjectSize", MongoDefaults.MaxMessageLength } }; var result = new IsMasterResult(); result.Initialize(command, document); Assert.AreEqual(MongoDefaults.MaxMessageLength + 1024, result.MaxMessageLength); }
public void TestMaxMessageLengthWhenServerSupplied() { var command = new CommandDocument("ismaster", 1); var document = new BsonDocument { { "ok", 1 }, { "maxMessageSizeBytes", 1000 }, { "maxBsonObjectSize", 1000 } }; var result = new IsMasterResult(); result.Initialize(command, document); Assert.AreEqual(1000, result.MaxMessageLength); }
public void TestOkMissing() { var command = new CommandDocument("invalid", 1); var document = new BsonDocument(); var result = new CommandResult(document) { Command = command }; try { var dummy = result.Ok; } catch (MongoCommandException ex) { Assert.IsTrue(ex.Message.StartsWith("Command 'invalid' failed. Response has no ok element (response was ", StringComparison.Ordinal)); } }
/// <summary> /// 增加数据分片 /// </summary> /// <param name="routeSvr"></param> /// <param name="replicaSetName"></param> /// <param name="shardingNames"></param> /// <returns></returns> public static CommandResult AddSharding(MongoServer routeSvr, string replicaSetName, List<string> shardingNames) { BsonDocument config = new BsonDocument(); BsonDocument cmd = new BsonDocument(); BsonDocument host = new BsonDocument(); string cmdPara = replicaSetName + "/"; foreach (var item in shardingNames) { cmdPara += SystemManager.ConfigHelperInstance.ConnectionList[item].IpAddr + ":" + SystemManager.ConfigHelperInstance.ConnectionList[item].Port.ToString() + ","; } cmdPara = cmdPara.TrimEnd(",".ToCharArray()); CommandDocument mongoCmd = new CommandDocument(); mongoCmd.Add("addshard", cmdPara); return ExecuteMongoCommand(mongoCmd, routeSvr); }
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()); } }
/// <summary> /// 数据集命令 /// </summary> /// <param name="Command">命令关键字</param> /// <param name="mongoCol">数据集</param> /// <param name="ExtendInfo">命令参数</param> /// <returns></returns> public static CommandResult ExecuteMongoColCommand(String Command, MongoCollection mongoCol, BsonDocument ExtendInfo) { var textSearchCommand = new CommandDocument { { Command, mongoCol.Name }, }; foreach (var item in ExtendInfo.Elements) { textSearchCommand.Add(item); } var mCommandResult = mongoCol.Database.RunCommand(textSearchCommand); RunCommandEventArgs e = new RunCommandEventArgs(); e.CommandString = textSearchCommand.ToString(); e.RunLevel = PathLv.CollectionLV; e.Result = mCommandResult; OnCommandRunComplete(e); return mCommandResult; }
/// <summary> /// 执行数据库命令 /// </summary> /// <param name="mongoCmd"></param> /// <param name="mongoDB"></param> /// <returns></returns> public static CommandResult ExecuteMongoDBCommand(CommandDocument mongoCmd, MongoDatabase mongoDB) { CommandResult rtn; try { rtn = mongoDB.RunCommand(mongoCmd); } catch (MongoCommandException ex) { rtn = ex.CommandResult; } RunCommandEventArgs e = new RunCommandEventArgs(); e.CommandString = mongoCmd.ToString(); e.RunLevel = PathLv.DatabaseLV; e.Result = rtn; OnCommandRunComplete(e); return rtn; }
protected override void BeginProcessing() { if (_CommandDocument == null) { if (Value == null) _CommandDocument = new CommandDocument(_CommandName, 1); else _CommandDocument = new CommandDocument(_CommandName, Actor.ToBsonValue(Value)); } try { var result = Database.RunCommand(_CommandDocument); WriteObject(new Dictionary(result.Response)); } catch (MongoCommandException ex) { WriteException(ex, null); } }
/// <summary> /// 执行数据集命令 /// </summary> /// <param name="CommandString"></param> /// <param name="mongoCol"></param> /// <returns></returns> public static CommandResult ExecuteMongoColCommand(String CommandString, MongoCollection mongoCol) { CommandResult rtn; BsonDocument cmd = new BsonDocument(); cmd.Add(CommandString, mongoCol.Name); CommandDocument mongoCmd = new CommandDocument() { cmd }; try { rtn = mongoCol.Database.RunCommand(mongoCmd); } catch (MongoCommandException ex) { rtn = ex.CommandResult; } RunCommandEventArgs e = new RunCommandEventArgs(); e.CommandString = CommandString; e.RunLevel = PathLv.DatabaseLV; e.Result = rtn; OnCommandRunComplete(e); return rtn; }
/// <summary> /// 增加数据分片 /// </summary> /// <param name="routeSvr"></param> /// <param name="replicaSetName"></param> /// <param name="lstAddress"></param> /// <remarks>注意:有个命令可能只能用在mongos上面</remarks> /// <returns></returns> public static CommandResult AddSharding(MongoServer routeSvr, String replicaSetName, List<String> lstAddress, String Name, Decimal MaxSize) { // replset/host:port,host:port String cmdPara = replicaSetName == String.Empty ? String.Empty : (replicaSetName + "/"); foreach (String item in lstAddress) { cmdPara += item + ","; } cmdPara = cmdPara.TrimEnd(",".ToCharArray()); CommandDocument mongoCmd = new CommandDocument(); mongoCmd.Add("addshard", cmdPara); if (MaxSize != 0) { mongoCmd.Add("maxSize", (BsonValue)MaxSize); } if (Name != String.Empty) { mongoCmd.Add("name", Name); } return ExecuteMongoSvrCommand(mongoCmd, routeSvr); }
/// <summary> /// 执行数据集命令 /// </summary> /// <param name="CommandString"></param> /// <param name="mongoCol"></param> /// <returns></returns> public static CommandResult ExecuteMongoColCommand(String CommandString, MongoCollection mongoCol) { CommandResult mCommandResult; BsonDocument BaseCommand = new BsonDocument(); BaseCommand.Add(CommandString, mongoCol.Name); CommandDocument mongoCmd = new CommandDocument(); mongoCmd.AddRange(BaseCommand); try { mCommandResult = mongoCol.Database.RunCommand(mongoCmd); } catch (MongoCommandException ex) { mCommandResult = ex.CommandResult; } RunCommandEventArgs e = new RunCommandEventArgs(); e.CommandString = CommandString; e.RunLevel = PathLv.CollectionLV; e.Result = mCommandResult; OnCommandRunComplete(e); return mCommandResult; }
/// <summary> /// 执行数据集命令 /// </summary> /// <param name="commandString"></param> /// <param name="mongoCol"></param> /// <returns></returns> public static CommandResult ExecuteMongoColCommand(string commandString, MongoCollection mongoCol) { CommandResult mCommandResult; var baseCommand = new BsonDocument { { commandString, mongoCol.Name } }; var mongoCmd = new CommandDocument(); mongoCmd.AddRange(baseCommand); try { mCommandResult = mongoCol.Database.RunCommand(mongoCmd); } catch (MongoCommandException ex) { mCommandResult = new CommandResult(ex.Result); } var e = new RunCommandEventArgs { CommandString = commandString, RunLevel = EnumMgr.PathLevel.CollectionAndView, Result = mCommandResult }; OnCommandRunComplete(e); return mCommandResult; }
/// <summary> /// Gets the current profiling level. /// </summary> /// <returns>The profiling level.</returns> public GetProfilingLevelResult GetProfilingLevel() { var command = new CommandDocument("profile", -1); return(RunCommandAs <GetProfilingLevelResult>(command, ReadPreference.Primary)); }
/// <summary> /// convertToCapped /// </summary> /// <param name="collectionName"></param> /// <param name="size"></param> /// <returns></returns> public static CommandResult convertToCapped(string collectionName, long size, MongoDatabase db) { var mongoCmd = new CommandDocument { { "convertToCapped", collectionName } }; mongoCmd.Add("size", size); return ExecuteMongoDBCommand(mongoCmd, db); }
/// <summary> /// 数据集分片 /// </summary> /// <param name="routeSvr"></param> /// <param name="sharingCollection"></param> /// <param name="shardingKey"></param> /// <returns></returns> public static CommandResult ShardCollection(MongoServer routeSvr, string sharingCollection, BsonDocument shardingKey) { var mongoCmd = new CommandDocument { { "shardCollection", sharingCollection }, { "key", shardingKey } }; return ExecuteMongoSvrCommand(mongoCmd, routeSvr); }
/// <summary> /// 数据库分片 /// </summary> /// <param name="routeSvr"></param> /// <param name="shardingDb"></param> /// <returns></returns> public static CommandResult EnableSharding(MongoServer routeSvr, string shardingDb) { var mongoCmd = new CommandDocument(); mongoCmd = new CommandDocument { { "enablesharding", shardingDb } }; return ExecuteMongoSvrCommand(mongoCmd, routeSvr); }
internal void Ping(MongoConnection connection) { var pingCommand = new CommandDocument("ping", 1); connection.RunCommand("admin.$cmd", QueryFlags.SlaveOk, pingCommand, true); }
internal void VerifyState( MongoConnection connection ) { CommandResult isMasterResult = null; try { try { var isMasterCommand = new CommandDocument("ismaster", 1); isMasterResult = connection.RunCommand("admin.$cmd", QueryFlags.SlaveOk, isMasterCommand); } catch (MongoCommandException ex) { isMasterResult = ex.CommandResult; throw; } var isPrimary = isMasterResult.Response["ismaster", false].ToBoolean(); var isSecondary = isMasterResult.Response["secondary", false].ToBoolean(); var isPassive = isMasterResult.Response["passive", false].ToBoolean(); var isArbiter = isMasterResult.Response["arbiterOnly", false].ToBoolean(); // workaround for CSHARP-273 if (isPassive && isArbiter) { isPassive = false; } var maxDocumentSize = isMasterResult.Response["maxBsonObjectSize", MongoDefaults.MaxDocumentSize].ToInt32(); var maxMessageLength = Math.Max(MongoDefaults.MaxMessageLength, maxDocumentSize + 1024); // derived from maxDocumentSize MongoServerBuildInfo buildInfo; try { var buildInfoCommand = new CommandDocument("buildinfo", 1); var buildInfoResult = connection.RunCommand("admin.$cmd", QueryFlags.SlaveOk, buildInfoCommand); buildInfo = new MongoServerBuildInfo( buildInfoResult.Response["bits"].ToInt32(), // bits buildInfoResult.Response["gitVersion"].AsString, // gitVersion buildInfoResult.Response["sysInfo"].AsString, // sysInfo buildInfoResult.Response["version"].AsString // versionString ); } catch (MongoCommandException ex) { // short term fix: if buildInfo fails due to auth we don't know the server version if (ex.CommandResult.ErrorMessage == "need to login") { buildInfo = null; } else { throw; } } this.isMasterResult = isMasterResult; this.maxDocumentSize = maxDocumentSize; this.maxMessageLength = maxMessageLength; this.buildInfo = buildInfo; this.SetState(MongoServerState.Connected, isPrimary, isSecondary, isPassive, isArbiter); } catch { this.isMasterResult = isMasterResult; this.maxDocumentSize = MongoDefaults.MaxDocumentSize; this.maxMessageLength = MongoDefaults.MaxMessageLength; this.buildInfo = null; this.SetState(MongoServerState.Disconnected, false, false, false, false); throw; } }
internal void VerifyState(MongoConnection connection) { CommandResult isMasterResult = null; bool ok = false; try { var isMasterCommand = new CommandDocument("ismaster", 1); isMasterResult = connection.RunCommand("admin.$cmd", QueryFlags.SlaveOk, isMasterCommand, false); if (!isMasterResult.Ok) { throw new MongoCommandException(isMasterResult); } var isPrimary = isMasterResult.Response["ismaster", false].ToBoolean(); var isSecondary = isMasterResult.Response["secondary", false].ToBoolean(); var isPassive = isMasterResult.Response["passive", false].ToBoolean(); var isArbiter = isMasterResult.Response["arbiterOnly", false].ToBoolean(); // workaround for CSHARP-273 if (isPassive && isArbiter) { isPassive = false; } var maxDocumentSize = isMasterResult.Response["maxBsonObjectSize", MongoDefaults.MaxDocumentSize].ToInt32(); var maxMessageLength = Math.Max(MongoDefaults.MaxMessageLength, maxDocumentSize + 1024); // derived from maxDocumentSize MongoServerBuildInfo buildInfo; var buildInfoCommand = new CommandDocument("buildinfo", 1); var buildInfoResult = connection.RunCommand("admin.$cmd", QueryFlags.SlaveOk, buildInfoCommand, false); if (buildInfoResult.Ok) { buildInfo = new MongoServerBuildInfo( buildInfoResult.Response["bits"].ToInt32(), // bits buildInfoResult.Response["gitVersion"].AsString, // gitVersion buildInfoResult.Response["sysInfo"].AsString, // sysInfo buildInfoResult.Response["version"].AsString // versionString ); } else { // short term fix: if buildInfo fails due to auth we don't know the server version; see CSHARP-324 if (buildInfoResult.ErrorMessage != "need to login") { throw new MongoCommandException(buildInfoResult); } buildInfo = null; } _isMasterResult = isMasterResult; _maxDocumentSize = maxDocumentSize; _maxMessageLength = maxMessageLength; _buildInfo = buildInfo; this.SetState(MongoServerState.Connected, isPrimary, isSecondary, isPassive, isArbiter); // if this is the primary of a replica set check to see if any instances have been added or removed if (isPrimary && _server.Settings.ConnectionMode == ConnectionMode.ReplicaSet) { var instanceAddresses = new List <MongoServerAddress>(); if (isMasterResult.Response.Contains("hosts")) { foreach (var hostName in isMasterResult.Response["hosts"].AsBsonArray) { var address = MongoServerAddress.Parse(hostName.AsString); instanceAddresses.Add(address); } } if (isMasterResult.Response.Contains("passives")) { foreach (var hostName in isMasterResult.Response["passives"].AsBsonArray) { var address = MongoServerAddress.Parse(hostName.AsString); instanceAddresses.Add(address); } } if (isMasterResult.Response.Contains("arbiters")) { foreach (var hostName in isMasterResult.Response["arbiters"].AsBsonArray) { var address = MongoServerAddress.Parse(hostName.AsString); instanceAddresses.Add(address); } } _server.VerifyInstances(instanceAddresses); } ok = true; } finally { if (!ok) { _isMasterResult = isMasterResult; _maxDocumentSize = MongoDefaults.MaxDocumentSize; _maxMessageLength = MongoDefaults.MaxMessageLength; _buildInfo = null; this.SetState(MongoServerState.Disconnected, false, false, false, false); } } }
/// <summary> /// Checks whether the server is alive (throws an exception if not). /// </summary> public virtual void Ping() { var command = new CommandDocument("ping", 1); RunAdminCommand(command); }
// private methods private void LookupServerInformation(MongoConnection connection) { IsMasterResult isMasterResult = null; bool ok = false; try { var isMasterCommand = new CommandDocument("ismaster", 1); isMasterResult = RunCommandAs <IsMasterResult>(connection, "admin", isMasterCommand); MongoServerBuildInfo buildInfo; try { var buildInfoCommand = new CommandDocument("buildinfo", 1); var buildInfoResult = RunCommandAs <CommandResult>(connection, "admin", buildInfoCommand); buildInfo = MongoServerBuildInfo.FromCommandResult(buildInfoResult); } catch (MongoCommandException ex) { // short term fix: if buildInfo fails due to auth we don't know the server version; see CSHARP-324 if (ex.CommandResult.ErrorMessage != "need to login") { throw; } buildInfo = null; } ReplicaSetInformation replicaSetInformation = null; MongoServerInstanceType instanceType = MongoServerInstanceType.StandAlone; if (isMasterResult.IsReplicaSet) { var peers = isMasterResult.Hosts.Concat(isMasterResult.Passives).Concat(isMasterResult.Arbiters).ToList(); replicaSetInformation = new ReplicaSetInformation(isMasterResult.ReplicaSetName, isMasterResult.Primary, peers, isMasterResult.Tags); instanceType = MongoServerInstanceType.ReplicaSetMember; } else if (isMasterResult.Message != null && isMasterResult.Message == "isdbgrid") { instanceType = MongoServerInstanceType.ShardRouter; } var newServerInfo = new ServerInformation { BuildInfo = buildInfo, InstanceType = instanceType, IsArbiter = isMasterResult.IsArbiterOnly, IsMasterResult = isMasterResult, IsPassive = isMasterResult.IsPassive, IsPrimary = isMasterResult.IsPrimary, IsSecondary = isMasterResult.IsSecondary, MaxDocumentSize = isMasterResult.MaxBsonObjectSize, MaxMessageLength = isMasterResult.MaxMessageLength, ReplicaSetInformation = replicaSetInformation }; MongoServerState currentState; lock (_serverInstanceLock) { currentState = _state; } SetState(currentState, newServerInfo); ok = true; } finally { if (!ok) { ServerInformation currentServerInfo; lock (_serverInstanceLock) { currentServerInfo = _serverInfo; } // keep the current instance type, build info, and replica set info // as these aren't relevent to state and are likely still correct. var newServerInfo = new ServerInformation { BuildInfo = currentServerInfo.BuildInfo, InstanceType = currentServerInfo.InstanceType, IsArbiter = false, IsMasterResult = isMasterResult, IsPassive = false, IsPrimary = false, IsSecondary = false, MaxDocumentSize = currentServerInfo.MaxDocumentSize, MaxMessageLength = currentServerInfo.MaxMessageLength, ReplicaSetInformation = currentServerInfo.ReplicaSetInformation }; SetState(MongoServerState.Disconnected, newServerInfo); } } }
/// <summary> /// Gets the current profiling level. /// </summary> /// <returns>The profiling level.</returns> public GetProfilingLevelResult GetProfilingLevel() { var command = new CommandDocument("profile", -1); return(RunCommandAs <GetProfilingLevelResult>(command)); }
public void TestGetStatsUsePowerOf2Sizes() { if (_server.BuildInfo.Version >= new Version(2, 2)) { _collection.Drop(); _database.CreateCollection(_collection.Name); // collMod command only works if collection exists var command = new CommandDocument { { "collMod", _collection.Name }, { "usePowerOf2Sizes", true } }; _database.RunCommand(command); var stats = _collection.GetStats(); Assert.IsTrue((stats.UserFlags & CollectionUserFlags.UsePowerOf2Sizes) != 0); } }
/// <summary> /// 修改用户(完全替换) /// </summary> /// <param name="user"></param> /// <param name="db"></param> /// <returns></returns> public static CommandResult updateUser(MongoUserEx user, MongoDatabase db) { var mongoCmd = new CommandDocument { { "updateUser", user.Username } }; mongoCmd.Add("pwd", user.Password); var roles = new BsonArray(); roles.AddRange(user.Roles.Select(x => x.AsBsonValue())); mongoCmd.Add("roles", roles); if (user.customData != null) { mongoCmd.Add("customData", user.customData); } return ExecuteMongoDBCommand(mongoCmd, db); }
/// <summary> /// 添加自定义角色 /// </summary> public static CommandResult createRole(MongoDatabase mongoDb, Role role) { var mongoCmd = new CommandDocument("createRole", role.Rolename); var privileges = new BsonArray(); privileges.AddRange(role.Privileges.Select(x => x.AsBsonDocument())); mongoCmd.Add("privileges", privileges); var roles = new BsonArray(); roles.AddRange(role.Roles.Select(x => x.AsBsonValue())); mongoCmd.Add("roles", roles); return ExecuteMongoDBCommand(mongoCmd, mongoDb); }
/// <summary> /// Gets the current database stats. /// </summary> /// <returns>An instance of DatabaseStatsResult.</returns> public virtual DatabaseStatsResult GetStats() { var command = new CommandDocument("dbstats", 1); return(RunCommandAs <DatabaseStatsResult>(command, _settings.ReadPreference)); }
/// <summary> /// 重新启动 /// </summary> /// <param name="primarySvr">副本组主服务器</param> /// <param name="config">服务器信息</param> /// <remarks>这个命令C#无法正确执行</remarks> /// <returns></returns> public static CommandResult ReconfigReplsetServer(MongoServer primarySvr, BsonDocument config, Boolean force = false) { var mongoCmd = new CommandDocument { { "replSetReconfig", config } }; mongoCmd.Add("force", force); return ExecuteMongoSvrCommand(mongoCmd, primarySvr); }
/// <summary> /// Runs a command on this database and returns the result as a TCommandResult. /// </summary> /// <param name="commandResultType">The command result type.</param> /// <param name="commandName">The name of the command.</param> /// <returns>A TCommandResult</returns> public virtual CommandResult RunCommandAs(Type commandResultType, string commandName) { var command = new CommandDocument(commandName, 1); return(RunCommandAs(commandResultType, command)); }
public void TestTextIndex() { if (_server.BuildInfo.Version >= new Version(2, 4, 0, 0)) { var enableTextSearchCommand = new CommandDocument { { "setParameter", 1 }, { "textSearchEnabled", true } }; var adminDatabase = _server.GetDatabase("admin"); adminDatabase.RunCommand(enableTextSearchCommand); if (_collection.Exists()) { _collection.Drop(); } _collection.Insert(new BsonDocument("x", "The quick brown fox")); _collection.Insert(new BsonDocument("x", "jumped over the fence")); _collection.CreateIndex(new IndexKeysDocument("x", "text")); var textSearchCommand = new CommandDocument { { "text", _collection.Name }, { "search", "fox" } }; var commandResult = _database.RunCommand(textSearchCommand); var response = commandResult.Response; Assert.AreEqual(1, response["stats"]["nfound"].ToInt32()); Assert.AreEqual("The quick brown fox", response["results"][0]["obj"]["x"].AsString); } }
internal void Connect( bool slaveOk ) { if (state != MongoServerState.Disconnected) { var message = string.Format("MongoServerInstance.Connect can only be called when state is Disconnected, not when state is {0}.", state); throw new InvalidOperationException(message); } State = MongoServerState.Connecting; connectException = null; try { endPoint = address.ToIPEndPoint(server.Settings.AddressFamily); var connectionPool = new MongoConnectionPool(this); try { var connection = connectionPool.AcquireConnection(null); try { try { var isMasterCommand = new CommandDocument("ismaster", 1); isMasterResult = connection.RunCommand("admin.$cmd", QueryFlags.SlaveOk, isMasterCommand); } catch (MongoCommandException ex) { isMasterResult = ex.CommandResult; throw; } isPrimary = isMasterResult.Response["ismaster", false].ToBoolean(); isSecondary = isMasterResult.Response["secondary", false].ToBoolean(); isPassive = isMasterResult.Response["passive", false].ToBoolean(); isArbiter = isMasterResult.Response["arbiterOnly", false].ToBoolean(); if (!isPrimary && !slaveOk) { throw new MongoConnectionException("Server is not a primary and SlaveOk is false."); } maxDocumentSize = isMasterResult.Response["maxBsonObjectSize", MongoDefaults.MaxDocumentSize].ToInt32(); maxMessageLength = Math.Max(MongoDefaults.MaxMessageLength, maxDocumentSize + 1024); // derived from maxDocumentSize var buildInfoCommand = new CommandDocument("buildinfo", 1); var buildInfoResult = connection.RunCommand("admin.$cmd", QueryFlags.SlaveOk, buildInfoCommand); buildInfo = new MongoServerBuildInfo( buildInfoResult.Response["bits"].ToInt32(), // bits buildInfoResult.Response["gitVersion"].AsString, // gitVersion buildInfoResult.Response["sysInfo"].AsString, // sysInfo buildInfoResult.Response["version"].AsString // versionString ); } finally { connectionPool.ReleaseConnection(connection); } } catch { connectionPool.Close(); throw; } State = MongoServerState.Connected; this.connectionPool = connectionPool; } catch (Exception ex) { State = MongoServerState.Disconnected; connectException = ex; throw; } }