【问题标题】:How to upsert a document in MongoDB .Net?如何在 MongoDB .Net 中插入文档?
【发布时间】:2015-11-23 17:17:47
【问题描述】:

我正在添加一个UpdateCustomer 方法,该方法将修改后的客户传递到数据库中。但是我在更新的文档上调用ReplaceOneAsync 时遇到了错误。

我咨询了以下exampleapi reference,它们都表示要传递ReplaceOneAsyncfilterdocument 参数。

但是具体的错误是因为参数不正确而抛出的,如下所述:

Error   1   The best overloaded method match for 'MongoDB.Driver.IMongoCollection<MongoDBApp.Models.CustomerModel>.ReplaceOneAsync(MongoDB.Driver.FilterDefinition<MongoDBApp.Models.CustomerModel>, MongoDBApp.Models.CustomerModel, MongoDB.Driver.UpdateOptions, System.Threading.CancellationToken)' has some invalid arguments 

Error   2   Argument 2: cannot convert from 'MongoDB.Bson.BsonDocument' to 'MongoDBApp.Models.CustomerModel'    

有人对理解错误有任何提示吗?

UpdateCustomer 方法:

public async Task UpdateCustomer(CustomerModel customer)
{          
    var collection = StartConnection();
    var filter = Builders<CustomerModel>.Filter.Where(x => x.Id == customer.Id);

    BsonDocument doc = new BsonDocument();

    doc["_id"] = customer.Id;
    doc["firstName"] = customer.FirstName;
    doc["lastName"] = customer.LastName;
    doc["email"] = customer.Email;

    //error thrown here on the ReplaceOneAsync params..
    await collection.ReplaceOneAsync(filter, doc);           
}

以及相关的StartConnection方法:

private static IMongoCollection<CustomerModel> StartConnection()
{
    var client = new MongoClient(connectionString);
    var database = client.GetDatabase("orders");
    //Get a handle on the customers collection:
    var collection = database.GetCollection<CustomerModel>("customers");
    return collection;
}

【问题讨论】:

    标签: c# .net mongodb-.net-driver mongodb-csharp-2.0


    【解决方案1】:

    您需要一直使用类型化集合,这意味着插入CustomerModel 的实例,而不是BsonDocument

    await collection.ReplaceOneAsync(filter, customer);
    

    或者使用BsonDocument 的无类型,但从一开始就这样做:

    var collection = database.GetCollection<BsonDocument>("customers");
    

    你得到这些编译错误是因为你混合了这两个选项。

    【讨论】:

    • 好的,这样就修复了不正确的参数错误,但是当我逐步执行该方法时,远程数据库上的值没有更新。不知道为什么当方法返回时,检查内容时过滤器和客户是正确的。这也不是连接问题,因为我的数据库内容正在加载,当我刷新我的数据网格时..任何想法如何进一步调试?
    • @BrianJ ReplaceOneAsync 实际上有结果。您可以查看它,看看是否有任何文件受到影响以及如何受到影响。
    • 我添加了一个结果变量,以便在执行后检查 ReplaceOneAsync 的内容,如下所示:` var result = await collection.ReplaceOneAsync(filter, customer);` 不太清楚如何破译细节当我踏入它时,图片链接在这里:picpaste.com/pics/result_debug-9QyUE5QF.1448319996.PNG你能建议吗?
    • @BrianJ 数据库中没有匹配的文档。您需要使用IsUpsert 标志:stackoverflow.com/a/30265529/885318
    • 好吧,这就是解决方案,但它没有达到预期的结果..一个新文档被添加到数据库中,原始文档仍然存在。我期待原件被删除或覆盖。那里有什么我想念的吗? @i3arnon
    【解决方案2】:

    这对我有用

    var filter = Builders.Filter.Where(x => x.Id == customer.Id); await Collection.ReplaceOneAsync(filter, item, new ReplaceOptions { IsUpsert = true });

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 2016-04-14
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 2014-06-21
      • 2016-05-02
      • 1970-01-01
      • 2012-08-29
      相关资源
      最近更新 更多