我正在尝试使用 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/