有几种推荐的树结构建模方法。查看官方文档中的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
主要优点是插入。你只需要知道你想要插入的东西的父母。不再有嵌套查找问题。