【问题标题】:Mongodb c# update a comment in n-nested comment chainMongodb c#更新n嵌套评论链中的评论
【发布时间】:2016-10-01 00:44:08
【问题描述】:

我发现了一些关于更新父文档的子文档的问题,但前提是您已经知道父/子树有多远。这是我的模型:

public class ParentThread
{
    public string id { get; set; }
    public string title { get; set; }
    public string body { get; set; }
    public List<Comment> Comments { get; set; }
}

public class Comment
{
    public string id { get; set; }
    public string body { get; set; }
    public List<Comment> Comments { get; set; }
}

我需要能够使用 Mongodb 的更新功能将新的 cmets 发送到父线程,而无需提交完整的线程。这是为了避免多个用户同时添加线程并且数据库覆盖它们的问题。问题是我不知道如何向 mongodb 指定它需要走多远才能将用户的评论添加到线程中。

我已经弄清楚如何查询文档并遍历树以找到要添加的目标评论,但我无法弄清楚如何将其作为 Update.Push() 方法的第一个参数传递.有什么想法吗?

【问题讨论】:

    标签: c# mongodb forum


    【解决方案1】:

    有几种推荐的树结构建模方法。查看官方文档中的parent references。这将线性化你的树。 Parent References 模式将每个树节点存储在文档中。除了树节点之外,文档还存储了节点父节点的 id。我的建议如下:

    // item is the base, comment is a thread comment, reply is a comment to a comment
    public enum ItemType { Item, Thread, Comment, Reply }
    
    public class Item {
      [BsonId] public string Id { get; set; }
      [BsonElement("body")] public string Body { get; set; }
      [BsonRepresentation(MongoDB.Bson.BsonType.String)]
      [BsonElement("type")] public virtual ItemType Type { get { return ItemType.Item; } }
      [BsonDefaultValue(null)]
      [BsonElement("parent")] public string ParentId { get; set; }
      [BsonDefaultValue(null)]
      [BsonElement("title")] public string Title { get; set; }
      public override string ToString() { return String.Format("{0};{1};{2};{3};{4}", Id, Type, ParentId, Body, Title); }
    }
    
    public class Thread : Item { public override ItemType Type { get { return ItemType.Thread; } } }
    
    public class Comment : Item { public override ItemType Type { get { return ItemType.Comment; } } } 
    
    public class Reply : Item { public override ItemType Type { get { return ItemType.Reply; } } }
    

    如何找到物品,驱动2.3版:

    IMongoCollection<item> col = ...
    // create index for parent column
    await col.Indexes.CreateOneAsync(Builders<Item>.IndexKeys.Ascending(x => x.ParentId));
    var root = await (await col.FindAsync(fdb.Eq(x => x.ParentId, null))).SingleOrDefaultAsync();
    var rootComments = await (await col.FindAsync(fdb.Eq(x => x.ParentId, root.Id))).ToListAsync();
    // same thing for queries for replies to comments
    

    主要优点是插入。你只需要知道你想要插​​入的东西的父母。不再有嵌套查找问题。

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 2012-09-17
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 1970-01-01
      • 2016-11-18
      • 2021-03-04
      相关资源
      最近更新 更多