本文为NoSQL数据模型设计系列的一部分。
此模式每个节点是一个文档,并且节点保存祖先节点的引用数组。
以下面分类层级为例
创建文档
db.categories.insertMany( [
{ _id: "MongoDB", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" },
{ _id: "dbm", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" },
{ _id: "Databases", ancestors: [ "Books", "Programming" ], parent: "Programming" },
{ _id: "Languages", ancestors: [ "Books", "Programming" ], parent: "Programming" },
{ _id: "Programming", ancestors: [ "Books" ], parent: "Books" },
{ _id: "Books", ancestors: [ ], parent: null }
] )
直接获取祖先节点
db.categories.findOne( { _id: "MongoDB" } ).ancestors
在ancestors字段上创建索引
db.categories.createIndex( { ancestors: 1 } )
可以获取子孙节点
db.categories.find( { ancestors: "Programming" } )
此模式比物化路径模式性能稍差,但是用起来更直接。
完整内容请查看NoSQL数据模型设计系列
网友评论