我正在尝试使用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);
但是得到了以下错误:
MyField中的$($)前缀字段'$toObjectId'。$toObjectId'对存储无效
这里的这个例子有效,但它并不理想,因为它强制我获取所有文档:
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_你为我指明了正确的方向,这个示例Mongo Db驱动程序C#聚合更新也帮助我编写了上面的代码。也非常感谢@dododo你的建议。