Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 更新嵌入式集合元素MongoDB_C#_.net_Mongodb_Mongodb .net Driver - Fatal编程技术网

C# 更新嵌入式集合元素MongoDB

C# 更新嵌入式集合元素MongoDB,c#,.net,mongodb,mongodb-.net-driver,C#,.net,Mongodb,Mongodb .net Driver,我们有下一个域模型: 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 {

我们有下一个域模型:

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驱动程序。 我们有集合用户和所有与特定用户相关的评论,我们存储在这个文档中

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


谢谢

这是您需要的代码:

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);

为了回答问题2,更多地了解您的用例将是有帮助的。您是否经常需要引用与他们相关的用户上下文之外的评论?通常,如果要嵌入它们,则不会同时为每个注释提供自己的唯一标识符。