2

Are failed commands (inserts, updated, deletes etc.) logged anywhere by Mongo DB?

I'm using the C# driver and some commands fail (e.g. inserts) due to duplicate unique key (enforced by an index), so I want to see in retrospect which documents were being inserted.
I would like to see the raw documents that failed, after the driver serialized them.

By the way, as I understand the Mongo oplog only contains successful commands.

1 Answer 1

1

Are failed commands (inserts, updated, deletes etc.) logged anywhere by Mongo DB?

I don't think they are, but maybe I haven't tried hard enough to find them yet.

However, you can log them in the application by setting the ClusterConfigurator on the MongoClientSettings like this

           //Build the initial settings from the MongoConnectionString
        MongoClientSettings settings = MongoClientSettings.FromConnectionString("MongoConnectionString");

        //Subscribe on the following events
        settings.ClusterConfigurator += cb =>
            {
                cb.Subscribe(delegate (CommandStartedEvent startedEvent) { Console.WriteLine($"Started: {startedEvent.Command} with OpId: {startedEvent.OperationId}"); });
                cb.Subscribe(delegate (CommandSucceededEvent succeededEvent) { Console.WriteLine($"Succeeded OpId: {succeededEvent.OperationId}"); });
                cb.Subscribe(delegate (CommandFailedEvent failedEvent) { Console.WriteLine($"Failed OpId: {failedEvent.OperationId}"); });
            };

        //Builld a MongoClient with the new Settings
        var client = new MongoClient(settings);

This example will only write the commands that are being exected and if which OperationId failed or succeeded.

But from here on you can extend it by keeping track of which command got started and what OperationId it runs on.

For a completed example you can see this Gist (as it seems like too much code to post here).

Which can be called as this:

        var settings = MongoClientSettings.FromConnectionString("MongoConnectionString");
        new MongoTracking().ConfigureTracking(settings);

        var client = new MongoClient(settings);

For the record, this does the logging in the application and not the database.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.