【问题标题】:Update embedded collection element MongoDB更新嵌入式集合元素 MongoDB
【发布时间】:2013-09-09 14:23:59
【问题描述】:

我们有下一个领域模型:

public class User
{
    public ObjectId Id { get; set; }

    public string Name { get; set; }

    public List<Comment> Comments { get; set; }
}

public class Comment
{
    public ObjectId Id { get; set; }

    public string Text { get; set; }
}

我们在项目中使用 MongoDB CSharp 驱动程序。 我们有集合“用户”和与特定用户相关的所有 cmets,我们存储在这个单个文档中。

问题 1:当我知道 UserIdCommentId 时,更新评论文本的正确方法是什么? 问题 2: 嵌入元素应该有自己的标识符吗?

谢谢

【问题讨论】:

  • 要回答问题 2,了解有关您的用例的更多信息会很有帮助。您是否经常需要在相关用户的上下文之外引用 cmets?通常,如果您要嵌入它们,您不会也为每条评论提供自己的唯一标识符。

标签: c# .net mongodb mongodb-.net-driver


【解决方案1】:

这是您需要的代码:

var update = Update.Set("Comments.$.Text", "new comment text");
var query = Query.And(
   Query<User>.EQ(u => u.Id, userId),
   Query<User>.ElemMatch(u => u.Comments, eq => eq.EQ(c => c.Id, commentId)));
userCollection.Update(query, update);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2022-01-22
    • 1970-01-01
    • 2018-12-25
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多