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

标签 c# mongodb mongodb-.net-driver

场景

我在 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/

相关文章:

c# - 关于单元测试

mongodb - sails 船。在 sails-mongo (mongodb) 上创建(和管理)索引的最佳方式

javascript - 使用 Mongoose 查找后如何更改子文档

python - 属性错误 : 'WriteConcern' object has no attribute 'acknowledged'

mongodb - 如何同时插入记录和数组元素?

MongoDB 类有参数但没有配置

c#进程将控制权交还给父进程问题

c# - 尝试调用方法时出错

MongoDB 和多个 C# 客户端线程

c# - 生成所有可能的组合