mongodb 如何设计多级结构?

各位,最近在学mongodb的时候有两个疑问,

(1)对于类似 文件夹-文件 这种多级的结构,如果使用mongodb,应该怎么设计集合的结构?
就比如这样的一个文件夹目录:

dirA
├── dirB
│   └── txtC.txt
├── txtA.txt
└── txtB.txt

在一个文件夹下,可以创建文件夹或者文件,然后文件夹下又可以继续重复这个过程,如果要保存类似这样的结构,应该怎么设计集合呢?就类似下面这样,该怎么定义结构?

{
    type: 'dir',
    name: 'dirA',
    files: [
        {type: 'dir', name: 'dirB', files:[{type: 'file', name: 'txtC.txt'}]},
        {type: 'file', name: 'txtA.txt'},
        {type: 'file', name: 'txtB.txt'}
    ]
}

(2)如何在mongodb中保存文件?

可能描述的不是很清楚问题,凑合理解吧。。。

阅读 2.4k
2 个回答
db.files.insertMany( [
  { _id: "1", "name": "dirA", "type": "dir", ancestors: [ ], parent: null }
  { _id: "2", "name": "dirB", "type": "dir", ancestors: [ "1" ], parent: "1" },
  { _id: "3", "name": "txtA.txt", "type": "file", ancestors: [ "1" ], parent: "1" },
  { _id: "4", "name": "txtB.txt", "type": "file", ancestors: [ "1" ], parent: "1" },
  { _id: "5", "name": "txtC.txt", "type": "file", ancestors: [  "1", "2" ], parent: "2" }
] )

唯一约束

db.files.createIndex( { "name": 1, "parent": 1}, { unique: true } )
MongoDB数据模型设计(3)具有祖先数组的模型树结构
作者:冰糕不冰
链接:https://juejin.cn/post/6982210696431796237#heading-12
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
基于 Linux 一切皆文件的设计思想,目录其实也是个文件,你甚至可以通过 vim 打开它,它也有 inode,inode 里面也是指向一些块。
image.png
详细讲解,Linux内核——文件系统(建议收藏) - Linux嵌入式的文章 - 知乎
https://zhuanlan.zhihu.com/p/505338841
{
    "_id": "dirA",
    "type": "dir",
    "name": "dirA",
    "files": [
        {
            "type": "dir",
            "name": "dirB",
            "files": [
                {
                    "type": "file",
                    "name": "txtC.txt"
                }
            ]
        },
        {
            "type": "file",
            "name": "txtA.txt"
        },
        {
            "type": "file",
            "name": "txtB.txt"
        }
    ]
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题