我正在嘗試使用 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);
}
uj5u.com熱心網友回復:
檢查這個:
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);
uj5u.com熱心網友回復:
此代碼示例有效:
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 的建議。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399227.html
上一篇:如何在MongoDB聚合中按字串而不是ObjectId分組?
下一篇:驗證檔案是否與我發送的資料相同
