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

如何用MongoDB C# Driver实现指定条件的联表更新操作

需求:用MongoDB C# Driver实现关联更新功能

我需要在MongoDB C# Driver中实现如下SQL语句的功能:

Update MyTable1 
set MyTable1.ColumnA = MyTable2.ColumnZ
from MyTable1
inner join MyTable2
    on MyTable2.PrimaryKeyValue = MyTable1.ForeignKeyValue
Where MyTable1.ColumnA is null;

我已写出对应的查询等价语句示例(MongoDB C# Driver代码):

IMongoClient client = new MongoClient("mongodb://host:port/");
IMongoDatabase database = client.GetDatabase("InventoryPOS");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("Collection1");

var options = new AggregateOptions() {
    AllowDiskUse = true
};

PipelineDefinition<BsonDocument, BsonDocument> pipeline = new BsonDocument[]
{
    new BsonDocument("$project", new BsonDocument()
            .Add("_id", 0)
            .Add("Collection1", "$$ROOT")), 
    new BsonDocument("$lookup", new BsonDocument()
            .Add("localField", "Collection1.ForeignKeyId_Property")
            .Add("from", "Collection2")
            .Add("foreignField", "PrimaryKeyId_Property")
            .Add("as", "Collection2")), 
    new BsonDocument("$unwind", new BsonDocument()
            .Add("path", "$Collection2")
            .Add("preserveNullAndEmptyArrays", new BsonBoolean(false))), 
    new BsonDocument("$project", new BsonDocument()
            .Add("Collection1.PropertyA", "$Collection1.PropertyA")
            .Add("Collection2.PropertyZ", "$Collection2.PropertyZ")
            .Add("_id", 0))
};

我的核心需求是:参照上述查询的关联逻辑,通过MongoDB C# Driver执行更新操作,将Collection1的PropertyA字段值设置为Collection2的PropertyZ字段值。

请问以上描述是否清晰说明了我的需求?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:33:10