Search code examples
c#mongodbmongodb-.net-driver

How to append Character to a String in a MongoDB Document with C#


I want to save logs in my Database but they come in Character by Character.

With my async code at the moment I obviously lose some updates:

var collection = db.GetCollection<ServerEntity>(ServerCollectionName);
var filter = Builders<ServerEntity>.Filter.Eq(server => server.ID, id);
var server = (await collection.FindAsync(filter)).First();
var update = Builders<ServerEntity>.Update.Set(server => server.Log, server.Log + message);
await collection.UpdateOneAsync(filter, update);

I've got a Document looking like this:

"_id": "8e93561bf28feeb5a01b6aa29a551822a8f2310ef46ddcfb837ae29bfaa9829d",
"Log": "Udat1\nUdt2\npae3\n",
"Config": {}

But it should look like this:

"_id": "8e93561bf28feeb5a01b6aa29a551822a8f2310ef46ddcfb837ae29bfaa9829d",
"Log": "Update1\Update2\Update3\n",
"Config": {}

Is there a way to simply append a character to the Log property.

Or can I at least perform a find and Update in the same operation with mongoDB.


Solution

  • I did it like @prasad_ suggested with aggregated pipelines

    public async Task AppendLog(string id, string message)
    {
        var filter = Builders<ServerEntity>.Filter.Eq(server => server.ID, id);
        var update = Builders<ServerEntity>.Update.Pipeline(UpdateQuery(message));
    
        await ServerCollection.UpdateOneAsync(filter, update);
    }
    
    private BsonDocument[] UpdateQuery(string message)
    {
        return new BsonDocument[]
        {
            BsonDocument.Parse(
                @"
                { 
                    $set: {
                        Log:
                            { 
                            $concat:[ '$Log', '" + message + @"' ] 
                        }
                    }
                }"
        )};
    }