【问题标题】:C# MongoDB pullFilter to remove string from string arrayC# MongoDB pullFilter 从字符串数组中删除字符串
【发布时间】:2022-11-27 12:20:13
【问题描述】:

我正在尝试做一个 pullFilter 并且可以让它在复杂类型上工作。

            await _Collection.UpdateOneAsync(
            Builders<Descriptor>.Filter.Eq(d => d.Id, id),
            Builders<Descriptor>.Update
                .Set(d => d.UpdatedBy, actioner)
                .Set(d => d.UpdatedOn, DateTime.Now)
                .PullFilter(d => d.Options, "Remove this one")
            );

但是,Options 是一个字符串值数组,我无法让它删除值“Remove this one”:

{
    "Name" : "Test",
    "Type" : NumberInt(1),
    "Options" : [
        "Testing",
        "Tested",
        "Remove this one"
    ]
}

这是我的错误信息:

message": "JSON reader was expecting a value but found 'Remove'."

我也试过这个:

        await _Collection.UpdateOneAsync(
            Builders<Descriptor>.Filter.Eq(d => d.Id, id),
            Builders<Descriptor>.Update
                .Set(d => d.UpdatedBy, actioner)
                .Set(d => d.UpdatedOn, DateTime.Now)
                .PullFilter(d => d.Options, d => d == "Remove this one")
        );

导致此错误:

"message": "{document} is not supported."

【问题讨论】:

    标签: c# arrays mongodb


    【解决方案1】:

    您应该使用 UpdateDefinitionExtensions.Pull<TDocument, TItem> Method (UpdateDefinition, FieldDefinition, TItem) 而不是 .PullFilter()

    await _Collection.UpdateOneAsync(
        Builders<Descriptor>.Filter.Eq(d => d.Id, id),
        Builders<Descriptor>.Update
            .Set(d => d.UpdatedBy, actioner)
            .Set(d => d.UpdatedOn, DateTime.Now)
            .Pull(d => d.Options, "Remove this one")
    );
    

    演示

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 2020-06-08
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2011-12-10
      • 1970-01-01
      相关资源
      最近更新 更多