No console output with MongoDB [duplicate] - c#

This question already has answers here:
How do I log my queries in MongoDB C# Driver 2.0?
(3 answers)
Closed 4 years ago.
I have connected MongoDB to .NET and I'm trying to save data into the database. The program works fine and my data is inserted into the database, but my understanding from the documentation is that I should be able to see everything that is occurring in the console window as well. This is my sample program that I'm working on.
static void Main(string[] args)
{
MainAsync().Wait();
Console.ReadLine();
}
static async Task MainAsync()
{
var client = new MongoClient("mongodb://localhost:27017");
IMongoDatabase db = client.GetDatabase("machines");
var collection = db.GetCollection<BsonDocument>("cranes");
var document = new BsonDocument
{
{ "code", BsonValue.Create("0x657")},
{ "departments", new BsonArray(new[] {"Mech", "Forge"}) },
};
await collection.InsertOneAsync(document);
}
This is the console output I am seeing when running the program.
I can see that the data has been succesffully added in MongoDB Compass, but I do not have any feedback in the console window.

You need to initiate MongoClient by using MongoClientSettings instead, and subscribe for command events there.
var url = MongoUrl.Create("mongodb://localhost:27017");
var settings = MongoClientSettings.FromUrl(url);
settings.ClusterConfigurator += b => b.Subscribe<CommandStartedEvent>(
e => Console.WriteLine($"MongoDB: {e.Command.ToJson()}")
);
var client = new MongoClient(settings);
...

Related

Error when creating ServiceBus Queue using Azure.Messaging.ServiceBus.Administration

I am (trying) to use this code to create ServiceBus Queue:
using Azure.Messaging.ServiceBus;
using Azure.Messaging.ServiceBus.Administration;
...
class blabla
{
private string connectionString = "Endpoint=sb://XXXX.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=XXXYYY";
private string queueName = "testqueue";
...
public doit()
{
var adminClient = new ServiceBusAdministrationClient(connectionString);
bool queueExists = adminClient.QueueExistsAsync(queueName).Result;
if (!queueExists)
{
var options = new CreateQueueOptions(queueName)
{
DefaultMessageTimeToLive = TimeSpan.FromDays(2),
LockDuration = TimeSpan.FromSeconds(45),
MaxDeliveryCount = 8,
MaxSizeInMegabytes = 2048
};
options.AuthorizationRules.Add(new SharedAccessAuthorizationRule(
"allClaims",
new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));
QueueProperties createdQueue = adminClient.CreateQueueAsync(options).Result;
}
}
}
but constantly getting this error:
System.AggregateException: One or more errors occurred. (SubCode=40900. Conflict. You're requesting an operation that isn't allowed in the resource's current state. To know more visit https://aka.ms/sbResourceMgrExceptions. . TrackingId:bc79fd98-73c8-4301-b6b9-05d0eae6ed6a_G17, SystemTracker:xxx.servicebus.windows.net:yyy, Timestamp:2021-05-09T00:24:57
Status: 409 (Conflict)
ErrorCode: 40900
Using old (NET) way with NamespaceManager from Microsoft.ServiceBus works with no problems.
var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
if (!namespaceManager.QueueExists(queueName))
{
namespaceManager.CreateQueue(queueName);
}
So, does anyone knows what am I doing wrong here?
*
Below is the updated working code, you need to make sure you have shared access policy with full access.
using Azure.Messaging.ServiceBus.Administration;
using System;
using System.Threading.Tasks;
namespace ServiceBusDemo
{
class Program
{
private static string connectionString = "Endpoint=sb://ns-servicebusshu.servicebus.windows.net/;SharedAccessKeyName=fullAccess;SharedAccessKey=oB+IsK8Aqp0/xfXnF9HCz6x9pqPIOysTXaJofSmHEYs=";
private static string queueName = "testqueue";
async static Task Main(string[] args)
{
await doit();
}
public static async Task doit()
{
var adminClient = new ServiceBusAdministrationClient(connectionString);
bool queueExists = await adminClient.QueueExistsAsync(queueName);
if (!queueExists)
{
var options = new CreateQueueOptions(queueName)
{
DefaultMessageTimeToLive = TimeSpan.FromDays(2),
LockDuration = TimeSpan.FromSeconds(45),
MaxDeliveryCount = 8,
MaxSizeInMegabytes = 2048
};
options.AuthorizationRules.Add(new SharedAccessAuthorizationRule("allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));
QueueProperties createdQueue = await adminClient.CreateQueueAsync(options);
}
}
}
}
Once you ran the application its successfully created the queue as below :
Maybe it's not your case... But if you have a TOPIC with the same name that you try to create your new QUEUE, QueueExistsAsync will return false, but you'll be spitted with this bizarre error at creation time. The fix is easy... changing the queue name or deleting the offending topic.
Sorry for the confusion.
My code (and Rahul Shukla as well) is working now (????).
I had to create a few new shared access policies with full access (????).
The third created started working (??).
The previous 2 I created are still not working (????).
There are no differences between the 3 policies created. Hence the question marks in my answer.
Posted question on MS NET SB forum about 1 out of 3 policies working. No answer/acknowledgment so far.

How can I get my collections (and data in general) from cloud.mongodb.com?

This is exactly my code. I've purposely let the Main method, so that you can see the whole thing.
static void Main(string[] args)
{
var client = new MongoClient("mongodb+srv:://MyDatabaseUser:MyDatabaseUserPassword#cluster0.re2kq.mongodb.net/LiviuTestDb?retryWrites=true&w=majority");
var database = client.GetDatabase("LiviuTestDb");
var myCollections = database.ListCollections();
}
I am getting a ConnectionTimeOutException. The credentials are correct - the user has read write to any database.
This is how my (only) cluster looks like (as simplistic as possible):
What can I try next?
What happens if you drop the db name from the connection string?
var client = new MongoClient("mongodb://MyDatabaseUser:MyDatabaseUserPassword#cluster0.re2kq.mongodb.net");

ZStandard Compression not working in MongoDB v4.2.7

Setup:
I'm using MongoDB v4.2.7 along with the .Net MongoDB driver v2.11.0(beta v) on a windows 10 machine.
Code
var mongoClientSettings = new MongoClientSettings();
mongoClientSettings.Compressors = new List<CompressorConfiguration>() {
new CompressorConfiguration(CompressorType.ZStandard)
};
var client = new MongoClient(mongoClientSettings);
IMongoDatabase testdb = client.GetDatabase("testdb");
var eaiRequestLogsCollection = testdb.GetCollection<EAIRequestsLogMDB>("EAIRequestsLogs");
eaiRequestLogsCollection.InsertMany(eAIRequestsLogMDBs);
Config
I've edited my mongod.cfg file as follows:
storage:
dbPath: C:\Program Files\MongoDB\Server\4.2\data
journal:
enabled: true
engine: "wiredTiger"
wiredTiger:
collectionConfig:
blockCompressor: "zstd"
Problem:
After the collection and the documents are added successfully I ran the db.printCollectionStats() on the mongo shell and I got block_compressor=snappy in the WiredTiger section while it should be block_compressor=zstd.
Below is a screenshot of the db.Stats(1024*1024*1024) output as well
"dataSize" : 0.08773485571146011 and "storageSize" : 0.009387969970703125
I posted a question on MongoDB Developer community Forums and was advised that my c# code was setting Network Compression rather than block_compressor.
This is the correct c# code that worked for me:
var client = new MongoClient("mongodb://127.0.0.1:27017");
IMongoDatabase testdb = client.GetDatabase("testdb");
testdb.CreateCollection("EAIRequestsLogs", new CreateCollectionOptions()
{
StorageEngine = new BsonDocument
{
{ "wiredTiger", new BsonDocument
{
{ "configString" , "block_compressor=zstd"}
}
}
}
});
var eaiRequestLogsCollection = testdb.GetCollection<EAIRequestsLogMDB>("EAIRequestsLogs");
Kind regards.

mongoDB C# Driver is not returning any data

I am having a problem where C# Driver is not returning any data with either using async-await or synchronous method.
When trying to run in the command line, it works perfectly, here's the snippet:
db.Collection_StudentResults.aggregate([ { $unwind: "$modules" }, { $match: { "studentNumber": "", "modules.code": "" } } ])
and here's how I have it setup in C#:
public static async Task<BsonDocument> getSingleStudentData(string studentNumber)
{
var client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("dbStudents");
var collection = db.GetCollection<BsonDocument>("Collection_StudentResults");
var aggregate = collection.Aggregate()
.Unwind("modules")
.Match(new BsonDocument { { "studentNumber", studentNumber } });
var result = await aggregate.ToListAsync();
return result.FirstOrDefault();
}
Drivers Used: v2.4.0
MongoDB Version: v3.2.10
In Collection_StudentResults, the first document contains the studentNumber and modules array, in the modules array each document has code field.
Please help!
Thanks
Sorry - my bad, bad bad bad...
I missed the db = db.getSiblingDB in my builder script - which caused the data to go into the root database.
All the best.

Building indexes in MongoDB with .NET driver 2.0

What's the new way to build indexes with the new driver 2.0?
There's no documentation whatsoever about this.
Apparently this now works with the new IndexKeysDefinitionBuilder<> interface but that's all I got so far.
You need to call and await CreateOneAsync with an IndexKeysDefinition you get by using Builders.IndexKeys:
static async Task CreateIndex()
{
var client = new MongoClient();
var database = client.GetDatabase("db");
var collection = database.GetCollection<Hamster>("collection");
await collection.Indexes.CreateOneAsync(Builders<Hamster>.IndexKeys.Ascending(_ => _.Name));
}
If you don't have a Hamster you can also create the index in a non-strongly-typed way by specifying the index's json representation:
await collection.Indexes.CreateOneAsync("{ Name: 1 }");

Categories

Resources