我如何在不使用Builders的情况下使用.net(c#)驱动程序更新mongo db中的文档?

问题描述 投票:1回答:3

我正在使用MongoDb .net驱动程序,其中我必须根据特定条件更新文档。

[这是我的find查询在c# mongo驱动程序中的样子

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

如何使用_id驱动程序而不使用Mongodb .net来基于某些Builders更新文档的特定字段?

**注:**

我已经尝试过此更新查询

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());

但是即使我收到这样的更新响应,它也不会更新值

{ "_t" : "Acknowledged" }
c# .net mongodb mongodb-.net-driver
3个回答
0
投票

您可以简单地ReplaceOne对象而不是对其进行更新,那样您就不会被迫使用构建器,而是将进行查找和替换。 2个数据库操作而不是一个。然后,您可以改为在内存中更新对象。

Collection.ReplaceOne(filter, replacement, new UpdateOptions() { IsUpsert = false });


0
投票

这是根据要求创建/更新/查找的示例:

using MongoDB.Entities; //Install-Package MongoDB.Entities
using MongoDB.Entities.Core;
using System;
using System.Linq;

namespace StackOverflow
{
    public class Customer : Entity
    {
        public string Name { get; set; }
        public Agent Agent { get; set; }
    }

    public class Agent
    {
        public string Name { get; set; }
        public string Email { get; set; }
    }

    public class Program
    {
        private static void Main()
        {
            new DB("test", "localhost");

            // create a customer with embedded agent
            var customer = new Customer
            {
                Name = "Customer A",
                Agent = new Agent { Name = "Agent Uno", Email = "[email protected]" }
            };
            customer.Save();

            // update customer name
            DB.Update<Customer>()
              .Match(c =>
                     c.ID == customer.ID &&
                     c.Agent.Email == "[email protected]")
              .Modify(c =>
                      c.Name, "Updated Customer")
              .Execute();

            // find updated customer
            var cst = DB.Find<Customer>()
                        .Match(customer.ID)
                        .Execute()
                        .Single();

            Console.WriteLine($"Customer Name: {cst.Name}");
            Console.Read();
        }
    }
}

0
投票

我使用这些选项在不使用任何第三方库的情况下实现了文档的更新

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 });
© www.soinside.com 2019 - 2024. All rights reserved.