You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用MongoDB C#驱动批量复制字段并生成ObjectId新字段

MongoDB C#驱动实现批量字段复制与ObjectId生成

一、批量复制现有字段到目标字段

C#驱动的强类型Set方法不支持直接引用当前文档的其他字段作为赋值源,需借助MongoDB原生更新表达式实现:

方法1:使用BsonDocument构建更新定义

// 将Id字段的值赋值给SemanticId
var updateDef = new BsonDocument("$set", new BsonDocument("SemanticId", "$Id"));
// 对集合所有文档执行更新
await collection.UpdateManyAsync(Builders<UserStory>.Filter.Empty, updateDef);

方法2:类型安全的表达式写法(推荐)

通过BsonExpression兼顾类型安全与原生表达式支持:

var updateDef = Builders<UserStory>.Update
    .Set(x => x.SemanticId, BsonExpression.Create("$Id"));
await collection.UpdateManyAsync(Builders<UserStory>.Filter.Empty, updateDef);

二、为新字段生成ObjectId

若需求是当目标字段(如SemanticId)不存在时自动生成新的ObjectId,可使用$ifNull操作符:

var updateDef = new BsonDocument("$set", new BsonDocument(
    "SemanticId", new BsonDocument("$ifNull", new BsonArray { "$SemanticId", BsonObjectId.GenerateNewId() })
));
await collection.UpdateManyAsync(Builders<UserStory>.Filter.Empty, updateDef);

如果需要“字段不存在时复制Id值,存在则保持原样”,调整$ifNull参数即可:

var updateDef = new BsonDocument("$set", new BsonDocument(
    "SemanticId", new BsonDocument("$ifNull", new BsonArray { "$SemanticId", "$Id" })
));
await collection.UpdateManyAsync(Builders<UserStory>.Filter.Empty, updateDef);

内容的提问来源于stack exchange,提问作者jgauffin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 16:12:37