c# - 使用 MongoDB C# 驱动程序更新所有文档的字段数据类型

标签 c# mongodb mongodb-.net-driver

我正在尝试使用 MongoDB C# 驱动程序将集合中所有文档的字段数据类型从字符串更新为 ObjectId。这个查询工作得很好:

db.getCollection('MyCollection').updateMany(
    { MyField: { $type: 2 } },
    [{ $set: { MyField: { $toObjectId: "$MyField" } } }]
);

但是我很难用 C# 编写相同的查询。 我已使用 UpdateManyAsync 尝试了以下查询:

var filter = new BsonDocument("MyField", new BsonDocument("$type", BsonType.String));
                var update = new BsonDocument {
                    { "$set", new BsonDocument("MyField", new BsonDocument("$toObjectId", "$MyField")) }
                };
var updateResult = await collection.UpdateManyAsync(filter, update);

但出现以下错误:

The dollar ($) prefixed field '$toObjectId' in 'MyField.$toObjectId' is not valid for storage

这里的示例可以工作,但并不理想,因为它迫使我获取所有文档:

var updateList = new List<WriteModel<BsonDocument>>();
var documents = await collection.Find(Builders<BsonDocument>.Filter.Empty).ToListAsync();

foreach (var document in documents)
{
    var id = document.GetElement("_id").Value.AsString;
    var myFieldValue = document.GetElement("MyField").Value.AsString;

    var filter = Builders<BsonDocument>.Filter.Eq("_id", id);
    var update = Builders<BsonDocument>.Update.Set("MyField", new BsonObjectId(ObjectId.Parse(myFieldValue)));
    updateList.Add(new UpdateOneModel<BsonDocument>(filter, update));
}

if (updateList.Any())
{
    var bulkWriteResult = await collection.BulkWriteAsync(updateList);          
}

最佳答案

检查一下:

        var pipeline = Builders<BsonDocument>
            .Update
            .Pipeline(new EmptyPipelineDefinition<BsonDocument>()
                .AppendStage<BsonDocument, BsonDocument, BsonDocument>("{ $set: { MyField: { $toObjectId: '$MyField' } } }"));
        coll.UpdateMany(
            new BsonDocument("MyField", new BsonDocument("$type", BsonType.String)),
            pipeline);

关于c# - 使用 MongoDB C# 驱动程序更新所有文档的字段数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70521700/

相关文章:

node.js - NodeJS 日志服务设计

MongoDB 远程备份和恢复

c# - 了解 MongoDB 新 C# 驱动程序的变化(Async 和 Await)

c# - 插入不创建 Id?

c# - 最好的 GridFS C# 驱动程序?

c# - app.UseRouting() 和 app.UseMvcWithDefaultRoute() 有什么区别?

c# - 如何使用正则表达式获取特定段?

arrays - 无法使用nodeJs更新mongodb中的嵌套数组,并且不会抛出错误

c# - 无法从 C# 调用 C++ 函数

c# - 如何将(1,11,12,2,All,Others)排序为(All,1,2,11,12,Others)?