C# MongoDB pullFilter从字符串数组中移除字符串

roejwanj  于 2022-11-28  发布在  Go
关注(0)|答案(1)|浏览(186)

我正在尝试做一个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."
mqxuamgl

mqxuamgl1#

您应该使用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")
);

演示

相关问题