트리 구조를 모델링하는 몇 가지 권장 방법이 있습니다. 공식 문서에서 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
주요 장점은 삽입입니다. 삽입하고자하는 것을 부모님 만 알면됩니다. 더 이상 내포 된 발견 문제가 없습니다.