public object stats(object scaleOrOptions) { var request = new Dictionary <string, object>(); request.Add("collStats", _name); var scale = scaleOrOptions.ToStringOrDefault().ToIntOrDefault(); if (scale.HasValue) { request.Add("scale", scale); } else if (scaleOrOptions is ExpandoObject) { scale = scaleOrOptions.GetProperty("scale").ToIntOrDefault(); if (scale.HasValue) { request.Add("scale", scale); } } var command = new BsonDocumentCommand <BsonDocument>(request.ToBsonDocument(), null); var result = this._collection.Database.RunCommand <BsonDocument>(command); return(result); }
private async Task ShardCollectionAsHashed(string collectionName, string shardKey) { try { if (CollectionExists(collectionName)) { return; } var shellCommand = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "shardCollection", $"Events.{collectionName}" }, { "key", new BsonDocument { { shardKey, "hashed" } } } }); await _mongoDatabase.RunCommandAsync(shellCommand).ConfigureAwait(false); } catch (Exception e) { if (e.ToString().Contains("Sharding is not supported for existing collections.", StringComparison.InvariantCultureIgnoreCase)) { return; } throw; } }
public async Task <Status> IsReadyAsync(CancellationToken cancellationToken) { var client = new MongoClient(_connectionString); IMongoDatabase adminDb = client.GetDatabase("admin"); var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "isMaster", 1 } }); BsonDocument res = await adminDb.RunCommandAsync(command); bool isMaster = res.GetValue("ismaster").AsBoolean; if (isMaster) { IClientSessionHandle session = await client.StartSessionAsync(); session.StartTransaction(); await session.CommitTransactionAsync(); } return(new Status { IsReady = isMaster, Message = res.ToString() }); }
private async Task TryCreateCollection <T>(string collectionName) where T : class { //Because we're using a shared throughput, we're forced to use partition keys //https://blog.jeremylikness.com/what-the-shard-cc29623503ad //get the partition key, based on type var partitionKey = GetPartitionKey <T>(); //Create the collection with a partition key var partition = new BsonDocument { { "shardCollection", $"{Database.DatabaseNamespace.DatabaseName}.{collectionName}" }, { "key", new BsonDocument { { partitionKey, "hashed" } } } }; var command = new BsonDocumentCommand <BsonDocument>(partition); try { await Database.RunCommandAsync(command); return; } catch (Exception e) { Console.WriteLine($"Unable to create a shard collection. going to try it with normal collection: { e.Message }"); } await Database.CreateCollectionAsync(collectionName); }
private int GetProfilingLevel() { BsonDocumentCommand <BsonDocument> command = new BsonDocumentCommand <BsonDocument>(new BsonDocument("profile", -1)); BsonDocument response = mongoDatabase.RunCommand(command); return(response.GetValue("was").AsInt32); }
/// <summary> /// Execute mongodb script with dotnet core /// </summary> /// <param name="mongoDbClient"></param> /// <returns></returns> private static async Task TestRunScript(IMongoClient mongoDbClient) { try { var database = mongoDbClient.GetDatabase("BookStoreDB"); const string script = @"db.Book.update({}, {$rename:{'Name':'BookName'}}, false, true)"; // db.RunCommand takes JSON as a parameter (docs) while you're trying to pass your script directly. // You can pass your script as a value where key is set to eval. // https://docs.mongodb.com/manual/reference/command/eval/#example // Why we need eval: https://jira.mongodb.org/browse/SERVER-17453?focusedCommentId=843013&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-843013 var doc = new BsonDocument() { { "eval", script } }; var command = new BsonDocumentCommand <BsonDocument>(doc); await database.RunCommandAsync(command); } catch (Exception e) { Console.WriteLine(e); // TODO: Handle execute script error throw; } }
public override void CopySet(string sourceSetIdentifier, string targetSetIdentifier, bool flushDestination = false) { if (flushDestination) { DropSet(targetSetIdentifier); } var sourceName = GetCollectionName(sourceSetIdentifier); var targetName = GetCollectionName(targetSetIdentifier); var aggDoc = new Dictionary <string, object> { { "aggregate", sourceName }, { "pipeline", new[] { new Dictionary <string, object> { { "$match", new BsonDocument() } }, new Dictionary <string, object> { { "$out", targetName } } } }, { "cursor", new Dictionary <string, object> { { "batchSize", 8192 } } } }; var doc = new BsonDocument(aggDoc); var command = new BsonDocumentCommand <BsonDocument>(doc); Database.RunCommand(command); }
private HomePageDashboardDto CalculateHomeDashboardDto() { HomePageDashboardDto output = new HomePageDashboardDto(); var client = new MongoClient(Configuration.LogMongoConnectionString); var database = client.GetDatabase("dotnetspider"); BsonDocumentCommand <BsonDocument> command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "dbStats", 1 }, { "scale", 1024 } }); var result = database.RunCommand(command); var storageSize = result.GetValue("storageSize").ToInt64(); var nodes = _nodeAppService.Query(new PaginationQueryInput { Page = 1, Size = 10 }); output.NodeTotalCount = (int)nodes.Total; output.NodeOnlineCount = _nodeAppService.GetOnlineNodeCount(); output.Nodes = nodes.Result; output.TaskCount = DbContext.Task.Count(t => !t.IsDeleted); output.RunningTaskCount = DbContext.Task.Count(t => t.IsRunning); output.LogSize = storageSize > G ? storageSize / G + "G" : storageSize / 1024 + "M"; return(output); }
private async Task ProcessNeedMongoMarkingsStateAsync(CryptContext context, string databaseName, CancellationToken cancellationToken) { var database = _mongocryptdClient.GetDatabase(databaseName); var commandBytes = context.GetOperation().ToArray(); var commandDocument = new RawBsonDocument(commandBytes); var command = new BsonDocumentCommand <BsonDocument>(commandDocument); BsonDocument response = null; for (var attempt = 1; response == null; attempt++) { try { response = await database.RunCommandAsync(command, cancellationToken : cancellationToken).ConfigureAwait(false); } catch (TimeoutException) when(attempt == 1) { _mongocryptdFactory.SpawnMongocryptdProcessIfRequired(); await WaitForMongocryptdReadyAsync().ConfigureAwait(false); } } RestoreDbNodeInResponse(commandDocument, response); FeedResult(context, response); }
private BsonDocument GetCollectionStats() { var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "collstats", LogsCollectionName } }); return(_db.RunCommandAsync(command).Result); }
public static BsonDocument GetStats <T>(this IMongoCollection <T> src) { var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "collstats", src.CollectionNamespace.CollectionName } }); return(src.Database.RunCommand(command)); }
public static void ClearCache <TDocument>(this IMongoCollection <TDocument> collection) { var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument() { { "planCacheClear", collection.CollectionNamespace.CollectionName } }); BsonDocument result = collection.Database.RunCommandAsync(command).Result; }
private Task Execute(IMongoDatabase database, CancellationToken token) { var command = new BsonDocumentCommand <dynamic>(new BsonDocument { { "logRotate", 1 } }); return(database.RunCommandAsync(command, cancellationToken: token)); }
public string RunCommand() { var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "dbStats", 1 }, { "scale", 1 } }); var result = _db.RunCommand <BsonDocument>(command); return(result.ToString()); }
public async Task <string> RunCommandAsync() { var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "dbStats", 1 }, { "scale", 1 } }); var result = await _db.RunCommandAsync <BsonDocument>(command); return(result.ToString()); }
public DateTime GetServerTime() { var serverStatusCmd = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "serverStatus", 1 } }); var result = db.RunCommand(serverStatusCmd); var localTime = result["localTime"].ToLocalTime(); return(localTime); }
public void ClearPlanCacheImages() { var doc = new BsonDocument() { { "planCacheClear", "images" } }; var command = new BsonDocumentCommand <BsonDocument>(doc); var response = database.RunCommand(command); }
public async Task <bool> GetConnectionStatusAsync() { var pingCommand = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "connectionStatus", 1 } }); var result = await _database.RunCommandAsync(pingCommand); var dict = result.ToDictionary(); return(dict.ContainsKey("ok") && dict["ok"].ToString() == "1"); }
private bool ContactDatabase() { //using database stats to verify database connection var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "dbstats", 1 }, { "scale", 1 } }); var result = this.database.RunCommand <BsonDocument>(command); return(true); }
public static async Task <Version> GetVersionAsync(this IMongoDatabase database) { var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "buildInfo", 1 } }); var result = await database.RunCommandAsync(command); return(Version.Parse(result["version"].AsString)); }
public virtual async Task <List <TEntity> > GetAllByCommandAsync(string mongoDbTextCommand) { var document = new BsonDocument() { { "eval", mongoDbTextCommand } }; var command = new BsonDocumentCommand <BsonDocument>(document); var response = await Task.Run(() => _context.Database.RunCommand(command)); return(response.ToList() as List <TEntity>); }
public async Task <bool> IsCollectionCappedAsync() { var command = new BsonDocumentCommand <BsonDocument>( new BsonDocument { { "collstats", CollectionName } }); var stats = await Context.Database.RunCommandAsync(command); return(stats["capped"].AsBoolean); }
public bool IsCollectionCapped() { var command = new BsonDocumentCommand <BsonDocument>( new BsonDocument { { "collstats", CollectionName } }); var stats = Context.Database.RunCommand(command); return(stats["capped"].AsBoolean); }
private static async Task CreateShards(IMongoDatabase database, string collectionName, string shardkeyName) { var partition = new BsonDocument { { "shardCollection", collectionName }, { "key", new BsonDocument { { shardkeyName, "hashed" } } } }; var command = new BsonDocumentCommand <BsonDocument>(partition); await database.RunCommandAsync(command); }
private void SetProfilingLevel(ProfilingLevels level, int minTime) { var command = new BsonDocumentCommand <BsonDocument>( new BsonDocument { { "profile", (int)level }, { "slowms", minTime } } ); var ret = mongoDatabase.RunCommand(command); int i = 0; }
//collection state public static string GetStats <TDocument>(this IMongoCollection <TDocument> collection) { var readCommand = new BsonDocumentCommand <BsonDocument>(new BsonDocument() { { "collStats", collection.CollectionNamespace.CollectionName }, //{ "scale", 1024 }, { "verbose", true }, { "indexDetails", true } }); BsonDocument result = collection.Database.RunCommandAsync(readCommand).Result; return(result.ToJsonIntended()); }
public async override Task InitializeAsync() { await base.InitializeAsync(); var client = new MongoClient(ConnectionString + "/?connect=direct"); BsonDocument rsConfig = CreateReplicaSetConfiguration(); var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "replSetInitiate", rsConfig } }); await client.GetDatabase("admin") .RunCommandAsync(command); await Initializer.WaitAsync(new MongoReplicaSetStatus(ConnectionString)); }
/* * Create a Collection */ private static void CreateCollection(IMongoDatabase mdb) { try { BsonDocumentCommand <BsonDocument> command = new BsonDocumentCommand <BsonDocument>( BsonDocument.Parse( "{ shardCollection: \"" + _databaseName + "." + _collectionName + "\", key: {iotId: \"hashed\"}}" )); mdb.RunCommand(command); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("Collection creation error: " + ex.Message); } }
private static void Statistics(string collectionName) { new BsonDocument { { "collstats", collectionName } }; var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "collstats", collectionName } }); var stats = mongoDb.RunCommand(command); Console.WriteLine($" * Collection : {collectionName}"); Console.WriteLine($" * Count : {stats["count"].AsInt32} documents"); Console.WriteLine($" * Average Doc Size: {stats["avgObjSize"].AsInt32} bytes"); Console.WriteLine($" * Total Storage : {stats["storageSize"].AsInt32} bytes"); Console.WriteLine("\n"); }
public static async Task <int> GetMajorVersionAsync(this IMongoDatabase database, CancellationToken ct = default) { var command = new BsonDocumentCommand <BsonDocument>(new BsonDocument { { "buildInfo", 1 } }); var document = await database.RunCommandAsync(command, cancellationToken : ct); var versionString = document["version"].AsString; var versionMajor = versionString.Split('.')[0]; int.TryParse(versionMajor, NumberStyles.Integer, CultureInfo.InvariantCulture, out int result); return(result); }
private static async Task<bool> IsCappedCollection(string collectionName, IMongoDatabase mongoDatabase) { var command = new BsonDocumentCommand<BsonDocument>(new BsonDocument { {"collstats", collectionName} }); var stats = await mongoDatabase.RunCommandAsync(command); return stats["capped"].AsBoolean; }
private BsonDocument GetCollectionStats() { var command = new BsonDocumentCommand<BsonDocument>(new BsonDocument { {"collstats", LogsCollectionName} }); return _db.RunCommandAsync(command).Result; }
private static async Task<bool> ConvertCollectionToCapped(string collectionName, IMongoDatabase mongoDatabase, long? cappedCollectionSize, long? maxNumberOfDocuments) { var command = new BsonDocumentCommand<BsonDocument>(new BsonDocument { {"convertToCapped", collectionName}, {"size",cappedCollectionSize ?? DefaultCappedCollectionSize }, {"max",maxNumberOfDocuments ?? DefaultCappedCollectionMaxDocuments} }); await mongoDatabase.RunCommandAsync(command); return await IsCappedCollection(collectionName, mongoDatabase); }