![](/img/trans.png)
[英]How to update document's array field's specific indexed value using Mongodb c# driver?
[英]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);
但出现以下错误:
'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 的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.