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

Update data type of field for all document using MongoDB C# 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);

此代码示例有效:

var filter = new BsonDocument("MyField", new BsonDocument("$type", BsonType.String));
var stage = new BsonDocument { { "$set", new BsonDocument { { "MyField", new BsonDocument { { "$toObjectId", "$MyField" } } } } } };
var pipeline = PipelineDefinition<BsonDocument, BsonDocument>.Create(stage);
var update = Builders<BsonDocument>.Update.Pipeline(pipeline);

var result = await collection.UpdateManyAsync(filter, update);

非常感谢@kanils_ 你给我指明了正确的方向,这个例子也帮助我写了上面的代码。也非常感谢@dododo 的建议。