我发现了一些有关更新父文档子项的问题,但只有当您已经知道父/子树的运行距离时才会这样。这是我的模特:
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的更新功能向父线程发送新注释,而无需提交完整的线程。这是为了避免多个用户同时添加线程并且数据库覆盖它们的问题。麻烦的是我不知道如何指定mongodb它需要走多远才能将用户的注释添加到线程中。
我已经弄清楚如何查询文档并遍历树以查找要添加的目标注释,但是我无法确定如何将其作为Update.Push()方法的第一个参数传递。有什么想法吗?
答案 0 :(得分:0)
有几种推荐的树结构建模方法。在官方文档中查看parent references。这将使你的树liniarize。 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
主要优点是插入。您只需要知道要插入的内容的父级。没有更多嵌套查找问题。