How to search in deep tree structure in MongoDB?

The easiest way to explain my situation is the standard file system structure, which is close to what I want to accomplish:

Folder A - Folder A2 -- File 1 -- File 2 - File 3 Folder B - Folder B2 - Folder B3 -- File 4 

There are fields in the folder:

 - _id - parents (in my case there can actually be multiple!) 

The file has fields

 - _id - targetFolder 

So basically the file can be very deep in the hierarchy.

How to efficiently search and structure my database in order to have deep hierarchies of folders, and any of them has files.

I want to be able to make a request that returns every file, for example. Folder A. How can i do this?

+4
source share
3 answers

I recommend the official MongoDb documentation of this. Storing trees in a database is not trivial, and each solution has its pros and cons. I experienced a successful materialized path model that is very effective at finding hierarchical objects, but expensive in modifying the tree, because you need to update every descendant of the node.

+5
source

Do not store them like a tree in mongo, at all! As Lucas said, here is a good explanation of how you do it. But your problem is that you need a connection to the chain from the root to folder A. You can do something like:

 { _id, name, type, parent: { grandparent : { parentOfGrandparent : {.......... 

So, to search for all the files in Folder A, you look for all the files, the parent - "Folder A". I think this will work:

 db.files.find( { parent : { "Folder A : { $exists: true } } } ); 
+2
source

I would do the following diagram:

Collection Name Files:

 { _id:id1 (generated unique id), name: file2 type: file parents:[id2,id3] -> parent directories FolderA2,FolderA } { _id:id2 (generated unique id), name: folderA2 type: directory parents:[id3] } { _id:id3 (generated unique id), name: folderA type: directory parents:[] } 

Then you can build a multicode index for parents and make a request as follows: db.files.find ({"parents": "id3", "type": "file"}) to find each file in folder A. The disadvantage of this scheme This is a complicated insertion, because when adding a new file or folder (directory), the parents must be filled in by getting the parent IDs from neighboring files or directories.

Hope this helps

+1
source

Source: https://habr.com/ru/post/1500602/


All Articles