使用

时间:2018-09-07 05:49:06

标签: c# mongodb nosql mongodb-.net-driver

我正在为MongoDB创建轻量级包装类,该类将在我的项目中使用。我陷入了要在同一文档中更新多个值的问题。我无法为此找到合适的解决方案。

我在MongoDB中的文档看起来像这样

_id : "7241b664-4943-4929-bcbf-18726cb74eeb"
Patterns :"Pattern1"
Description :"M1"
Update : "U1"

_id    :    "b6c8beb9-01a5-4a59-b5da-f2ef6501a86b"
Patterns : "Pattern2"
Description  : "M2"
Update  : "U2"

_id    :    "9cd91fa0-3e49-413a-8ad4-c1830aaae841"
Patterns   :  "Pattern3"
Description : "M3"
Update    :    "U3"

_id    :    "b597d1ec-160c-4c2c-8b67-ff36f4aa51ca"
Patterns     :    "Pattern4"
Description    :    "M4"
Update    :    "U4"

现在假设我要为{p>更新DescriptionUpdate字段

   _id = "7241b664-4943-4929-bcbf-18726cb74eeb"

我正在为MongoDB创建一个通用的轻量级库,使用该库的客户端不应该依赖MongoDB.Driver或BSON或其任何DLL文件。

当我想为文档中的单个记录更新单个字段时,可以这样做。下面是我的代码:

 public void Update<T, Tfield>(string collectionName, Expression<Func<T, bool>> filter, Expression<Func<T, Tfield>> field, Tfield value)
    {
        if (filter == null) throw new ArgumentNullException("filter is empty");
        var collection = GetCollection<T>(collectionName);
        var update = Builders<T>.Update.Set(field, value);
        collection.UpdateMany(filter, update);
    }

使用这种方式是这样的:

public void TestMongoUpdate()
    {
        var p = new RegexPatterns();
        var connectionString = "mongodb://localhost:27017";
        var collection = "MessagePatterns";
        //var filter = "{ _id: 'def8437e-d101-453e-a498-05e129b8dd39'}";
        var mongo = new Mongo(connectionString);
        mongo.DatabaseName = "MongoDB";
        var id = "7241b664-4943-4929-bcbf-18726cb74eeb";
        var pattern = new RegexPatterns();
        pattern._id = id;
        pattern.Patterns = "mypattern";
        pattern.Description = "mydesc";
        mongo.Update<RegexPatterns, string>(collection, (x => x._id == id),(y => y.Patterns),pattern.Patterns);
        Assert.True(true);
    }

使用上述测试方法,我可以为提供的ID更新Patterns的值。现在,我想更新提供的ID的PatternsDescription字段,但是我实在不敢让这种方法有效地更新多个字段。

我尝试了以下测试用例来执行此操作,但是它不起作用。我做错了什么。

public void TestMongoUpdateMulti()
    {
        var p = new RegexPatterns();
        var connectionString = "mongodb://localhost:27017";
        var collection = "MessagePatterns";
        //var filter = "{ _id: 'def8437e-d101-453e-a498-05e129b8dd39'}";
        var mongo = new Mongo(connectionString);
        mongo.DatabaseName = "MongoDB";
        var id = "7241b664-4943-4929-bcbf-18726cb74eeb";
        var pattern = new RegexPatterns();
        pattern._id = id;
        pattern.Patterns = "mypattern";
        pattern.Description = "mydesc";
        mongo.Update<RegexPatterns, RegexPatterns>(collection, (x => x._id == id), (y => pattern), pattern);
        Assert.True(true);
    }

我该如何解决?

这是使用.NET标准2.0和最新的MongoDB.Driver的C#语言。

0 个答案:

没有答案