gpt4 book ai didi

c# - 更新mongo文档整体或特定字段

转载 作者:行者123 更新时间:2023-12-03 08:54:25 25 4
gpt4 key购买 nike

场景

我在 mongodb 中有一个对话文档,我必须将消息添加到消息数组并更新最后发送的日期,请参阅下面的架构。

{ 
"_id" : NumberInt(5),
"CurrentOwnerId" : NumberInt(9),
"LastSent" : ISODate("2019-06-21T11:57:32.861+0000"),
"Messages" : [
{
"_id" : BinData(3, "nuC1iYTKtkGzSuv7pVHsKg=="),
"MessageContent" : "Hi There",
"Status" : "Pending",
"DateSent" : ISODate("2019-06-21T11:57:32.861+0000"),
"Method" : "Slack"
}
]
}

我的问题

简单地读出整个文档(使用 BsonId)并通过 C# 整体更新文档(即将我的消息推送到数组并设置最后发送日期和)是否会更有效?然后使用驱动程序更新整个文档,或者使用 $set 和 $push 运算符对数据库进行两次调用,以实现我想要做的事情。

最佳答案

正如 Eduardo Hitek 所说,您可以在单个查询中设置多个属性。因此,您可以更新实体,而不必先像这样从数据库中检索实体:

    //Build an Id Filter
var idFilter = Builders<Chat>.Filter.Eq(x => x.Id, "1");


var message = new Message() { MessageContent = "Hey!", Method = "Slack" };

//Build an update definition to add the message
var addMessage = Builders<Chat>.Update.AddToSet(x => x.Messages, message);
//Build an update definition to set the LastSent property
var setLastSent = Builders<Chat>.Update.Set(x => x.LastSent, DateTime.Now);
//Combine both update definitions
var combinedUpdate = Builders<Chat>.Update.Combine(addMessage, setLastSent);

//Execute the query.
db.GetCollection<Chat>("ChatCollection").UpdateOne(idFilter, combinedUpdate);

像这样更新实体的额外好处是它是自动完成的。

关于c# - 更新mongo文档整体或特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56703207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com