Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search against a deep tree-like structure in MongoDB?

The simplest way to explain my situation is with standard filesystem 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

Folder has fields:

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

File has fields

- _id
- targetFolder

So, basically a file could be very deep in the hierarchy.

How do I search and structure my DB efficiently so that I can have deep folder hierarchies, with any of them having files.

I want to be able to do a query that returns every file under e.g. Folder A. How could I do this?

like image 573
Ahmed Avatar asked Feb 16 '23 09:02

Ahmed


2 Answers

I recommend the MongoDb official documentation of this topic. Storing trees in database is non trivial and every solution have its pro and cons. I experienced successfully materialized paths model, which is very efficient on hierachy search but expensive on tree modification because you have to update every descendant node.

like image 137
LFI Avatar answered Feb 18 '23 03:02

LFI


Not store them as a tree in mongo, at all! Like Lucas said, here is a good explanation on how you do it. But your problem is that you need a chained join from the root to Folder A. You could do something like:

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

So to search for all files of Folder A you search for all files that parent is "Folder A". I think this will work:

db.files.find( { parent : { "Folder A : { $exists: true } } } );
like image 37
Discipol Avatar answered Feb 18 '23 02:02

Discipol