Search code examples
c#.netmongodbmongodb-.net-driver

How can i update document in mongo db using .net(c#) driver without using Builders?


I am using MongoDb .net driver in which i have to update document based on certain condition.

Here is how my find query looks like in c# mongo driver

DbService.conversations.Find (new BsonDocument ("_id", new ObjectId ("obje-id-here"))).FirstOrDefault ();

How can i update specific field of document based on certain _id using Mongodb .net driver without using Builders?

**Note : **

I have tried this update query

var updateResultFromQuery = await DbService.conversations.UpdateOneAsync(Builders<RawBsonDocument>.Filter.Eq("_id", "5e01a89e5f317324780b7f83"),Builders<RawBsonDocument>.Update.Set("visitorName", "Guest41815"));
Console.WriteLine("after update response --- "+updateResultFromQuery.ToJson());

But it's not updating the value even i am receiving update response like this

{ "_t" : "Acknowledged" }

Solution

  • I achieved updating my document without using any third party library using these options

    var filter = new BsonDocument(new Dictionary<string, dynamic> () {
      {
        "_id",  new BsonObjectId("object-id-here")
      },
      {
        "assigned_to.email" , agentEmail
      }
    });
    
    var updateDoc = new BsonDocument(new Dictionary<string, dynamic> () {
      {
        "$set", new BsonDocument("assigned_to.$.avgResponseTime", Convert.ToDouble(obj.agentChatAvgResponseTime))
      }
     });
    var updateQueryResult = DbService.conversations.UpdateOne(filter, updateDoc, new UpdateOptions {IsUpsert = false });